#archived-code-advanced

1 messages ยท Page 38 of 1

icy aspen
fresh salmon
#

So you can do

newList = new List<float>(oldList);

It will create a new List that holds the same items as the old one, but that does not point to the old List

icy aspen
#

ok, thank you very much

regal olive
#
    public float maxTime = 1000f;

    IEnumerator CheckChance(float floatValue)
    {
        float chance = 0.5f;
        floatValue = Mathf.Clamp(floatValue, 1, 200);
        float time = (floatValue / 200) * (maxTime - minTime) + minTime;
        while (true)
        {
            float random = Random.Range(0f, 1f);
            if (random < chance)
            {
                AddMoney();
                yield return new WaitForSeconds(time);
            }
            else
            {
                yield return new WaitForSeconds(time);
            }
        }
    }``` Someone know how I can make it, so it is Updating the function based on the time and the InputfieldValue. I want it, so when the InputfieldValue is 1, the seconds are 1. When the InputFieldValue is 200, the time is 1000 seconds.
fresh salmon
regal olive
# fresh salmon Can use a remap function to do that. It's a combination of `Mathf.Lerp` and `Mat...

I already got it.```private IEnumerator CheckChance(string inputFieldValue)
{
inputFieldValue = PlayerPrefs.GetString("InputFieldValue");
// Try to parse the input field value to a float
if (float.TryParse(inputFieldValue, out float floatValue))
{
floatValue = Mathf.Clamp(floatValue, 1, 200);
float time = Mathf.Pow(floatValue, 1.6f) * 10f;
Debug.Log($"TIME IS {time}");
yield return new WaitForSeconds(time);
AddMoney();

    }

}``` How can I make it, so it is not constantly calling the Addmoney function after the time?
fresh salmon
#

This will already call it once

#

Unless you call the coroutine repeatedly

regal olive
#
    {

        // Get the current value of moneyValue
        moneyValue = PlayerPrefs.GetInt("MoneyValue");

        Debug.Log(moneyValue);

        // Get the text/value from the input field
        string value = inputField.text;

        Debug.Log(value);

        CheckChanceCo = CheckChance(floatValue);
        StartCoroutine(CheckChanceCo);


    }````
#

Is this repeatly?

stiff hornet
#

yes every frame Update is called

fresh salmon
#

Yes, this is ran each frame

regal olive
#

How can I change it?

stiff hornet
#

Change Update to Start?

fresh salmon
#

If you need to only call it a specific times you can use a bool value and an if statement that will only run the method when it's true, for example

stiff hornet
#

i'm not sure what you are trying to accomplish though (one off or every so often)

lime vine
#

Hello everyone! I'm looking for a solution for calculating the part of screen coords of camera frustum that is under the ground (below 0 on Y).
Essentially I want to show some picture on that part, to achieve this effect, but without 3d model.

I don't need code, just a way to calculate it ๐Ÿ™‚
Thanks!

regal olive
fresh salmon
#

So repeatedly, use a coroutine for that which yields 10 seconds

lime vine
regal olive
humble onyx
#

or a post process if you are using the build in pipeline

lime vine
fresh salmon
fresh salmon
lime vine
humble onyx
#

or i may have missed some information

lime vine
lime vine
regal olive
fresh salmon
#

No that would be in a coroutine

#

Use a bit of logic, you cannot yield when not in a coroutine

humble onyx
#

assuming the ground is flat

lime vine
humble onyx
lime vine
humble onyx
lime vine
humble onyx
#

in theory you would have the edge points of the Near clip plane of the camera
If you would draw a line from the top to the botton one and the solve for y been 0

#

then you would have the point on the outer edges that have the y position at 0

misty glade
#

I have this dialog box that is dynamic and showing little prefabs for all of a player's crew. There's 65 crew, so this dialog box is doing some .. heavy lifting on Instantiating these prefabs. The performance sucks though - 650ms to open the dialog. Any ideas on how I can improve this? 400 ms to initialize the icons themselves..

I don't know that I can just create the dialog and cache it since the crew are changing all the time (that's pretty much what the gameplay is.. creating clones, assigning them to missions, etc)

#

It looks like a big chunk of the instantiate time is on the setting of the sprite. Any tricks to optimize that?

misty glade
#

I mean, it's not much time - just 9ms, but.. doing it 65 times adds up maybe?

undone coral
#

why does file.read appear at all?

#

also, aren't these sprites atlased?

misty glade
#

Well, it's my understanding that the atlasing and packing isn't optimized in the player/editor

#

Maybe this is a non-issue in builds

undone coral
#

it seems odd

#

i've never seen this in my sprites based games

misty glade
#

looks like almost 80% of that call is the file/read stuff

undone coral
#

what is the file format?

#

in the Assets/ folder

misty glade
#

png, i think

#

I'm sorta not directly reading them, but not sure if that matters - I have an SO that has the references and I get the reference to the texture through that

#

Maybe that's where the file reading is being done?

undone coral
#

hmm

#

in order to load the image, if i graphed the dependencies of unity assets between the code and the image, would there be any assets that were loaded with Resources.Load?

misty glade
#

looks like the most time is literally just:

UnityEngine.UI.Image.sprite = UnityEngine.Sprite;
undone coral
#

okay try this

misty glade
#

I don't think so?

#

brb

undone coral
#

okay

undone coral
# misty glade brb

when you get back, try dumping all the sprites onto a Sprite[] on a game object in your scene.

#

and then see what happens

misty glade
#

Sorry, had to get the door. I'm not doing any Resources.Load calls myself, but I don't know what's going on under the hood for how SOs manage themselves

#

What do you mean dumping them all into the scene? Just.. a naked object that I assign a bunch of sprites to?

#

I mean, I have several thousand sprites in the SO library

lime vine
misty glade
#

They're also nested, if that makes any difference.. IE, there's a CrewDatabaseSO that has all the CrewSOs, each of which have a bunch of poses and wave files and stuff

humble onyx
misty glade
humble onyx
#

yes i was going the plane intersection route

undone coral
#

a naked object

#

it will force them to be loaded

#

in a clean way

humble onyx
#

@lime vinehttps://hatebin.com/fdzliqwpor

undone coral
#

this will resolve if it's a feature or a bug

#

right now it sounds like possibly a feature

misty glade
#

I'm thinking that the bottleneck here is actually loading the scriptable object textures in.. It's hard to google this since it's a bit more advanced. Is there reference source available for unity? I forget, or don't recall what pricing tier it's attached to

undone coral
#

if the scene references the scriptable objects, and the scriptable objects reference the textures, they are loaded

#

on scene load

#

so right now it sounds like a bug

misty glade
#

I mean I suppose alternatively I could load all those textures into memory at the start of the app and keep them cached instead of on demand, but that seems maybe wastey if a user isn't seeing all of the crew all that often

undone coral
#

they are already loaded in memory

lime vine
misty glade
#

the scene doesn't unfortunately, i'm finding it on demand

undone coral
#

via resources.load ๐Ÿ™‚ ?

misty glade
#

no, but i had to double check

#

my two normal methods are to either FindOBjectOfType (usually only for low volume MBs) or to manually link it

#

and in this case, I'm manually linking it to the prefab

lime vine
undone coral
# misty glade

as long as this game object is in the scene, it has transitively loaded all the sprites

#

you ought to see them in the memory profiler

misty glade
#

well, this isn't since it's a prefab

humble onyx
undone coral
#

is the prefab referenced in the scene?

misty glade
#

I'm assuming that's not a problem

#

Indirectly, yeah

undone coral
#

how is it put into the scene? via resources.load?

#

define indirectly

misty glade
#

I never use resources.load

#

so .. there's a single MB in the scene with nested prefabs and/or MBs that.. have references to the prefabs they need

undone coral
#

okay

#

so it's referenced directly

#

then it's loaded

misty glade
#

lemme snap this particular one in the hierarchy

lime vine
misty glade
#

yeah

undone coral
#

you will see it in the memory profiler

#

i think this is probably a bug then, maybe related to a compression setting, an atlas setting,e tc.

misty glade
undone coral
#

as long as the path of dependencies between an object in your scene and the sprite does not transit a resources.load, you are directly referencing and hence loading the sprite on scene load

misty glade
#

PrimeIconV3(Clone) is an instance of the icon prefab - the SelectCrewPanel creates a bunch of those, but the prefab is linked to that MB so it's never loading it from a Resource

undone coral
#

that's how unity knows what to build into your game, and why it must build the entire contents of Resources/ directories

#

ya

misty glade
#

hm.. so should I still try that Sprite[] object?

undone coral
#

well

#

this is a bug

#

it shouldn't be doing that

#

unity*

#

so my first try would be that

#

because there might be something iffy about the sprites

misty glade
#

It could be related to player/editor behaviour (ie, the textures aren't optimized)

undone coral
#

hmm but i've done this so much and so many times

#

i've never seen it

#

i've seen some weird apeparance of stuff double-compressed due to atlases but that's it

misty glade
#

like.. i'm not familiar with the build process and how it optimizes/changes how textures are referenced, but that seems like it would make sense to me

#

but since opening/closing this dialog is a pretty hot path item.. 600ms is really unacceptable .. and it seems like ~350ms of that is file loading

undone coral
#

yeah it seems very glitchy

#

try referencing all the sprites

misty glade
undone coral
#

see what happens

misty glade
#

is that meaningful?

#

(the filename thing - it's something in /Library)

undone coral
#

hmm

#

i never paid close enough attention in other places to know

misty glade
#

oh cool this is interesting, if you click on the file.read in the profiler, it "bloops" the asset in the hierarchy so you can see what it is

#

it's definitely the textures

#

so .. I'm assuming that this is just reading the texture directly from disk and .. i'll have to do a build and see if the same performance problem is on the final product

undone coral
#

uniformnormal?

#

are these files imported with read/write?

misty glade
#

ha - nothing to do with "Normal" in the math sense or "Uniform" as in homogeneous

undone coral
#

okay lol

#

like uniform

#

as in outfit

misty glade
#

That's Dr Bubbles....... wearing his Uniform...... in a Normal pose (versus Victory or Defeat)

undone coral
#

i gotchyu

misty glade
#

Yeah like many of the characters have happy/sad/casual/etc poses for all the cutscenes

#

our artist is pretty damn good

#

etc

#

I'm gonna defer digging into this for now.. I will have to test/profile this in a build to see if it's the same.. I also have been meaning to upgrade the version we're using before then anyway, just in case it's some bug that's been fixed in the last year or whatever. ๐Ÿคทโ€โ™‚๏ธ As always, thanks for your eyeballs and brain cpu cycles drp

misty glade
#

Another profiling question for anyone:

#

450ms as I load my main scene. I haven't caught it yet but it seems like this sometimes takes 5+ sec. Restarting unity always fixes it. Should I care about this?

flint geyser
#

How would I properly do something like this in Unity?

bool alreadyTaken = false;
Monitor.Enter(_lockObject, ref alreadyTaken);
if (alreadyTaken) return;```
arctic lake
#

I watched a video on how to compress a unity file into one .exe file. It told me to use winrar. My question is will other people need to have winrar installed to open my now compressed .exe file.

flint geyser
#

Full function

        private async void TryStartCountDown()
        {
            _timeLeft = _animationLengthAfterLastMoveInSec;
            bool alreadyTaken = false;
            Monitor.Enter(_lockObject, ref alreadyTaken);
            if (alreadyTaken) return;
            
                Debug.Log(_timeLeft);
            while (_timeLeft > 0f)
            {
                _timeLeft -= Time.deltaTime;
                await UniTask.NextFrame();
            }
            
            _boolSetter.SetBoolToFalse();
        }```
stiff hornet
warm forge
stiff hornet
#

they would still need to run the game exe afterwards (i'm assuming as in can't see anywhere where it says you can run something afterwards) where it was extracted to

misty glade
#

I have so many questions

flint geyser
#

But I don't want it to be called multiple times

arctic lake
misty glade
#

K just .. not sure why you're not using something simpler instead of trying UniTask and async and ... "boolSetter" which is .... like, memeworthy, perhaps unintentionally so

long ivy
flint geyser
#

Ah my stupidity

stiff hornet
#

you could test by using a different computer if you have one

#

or uninstall winrar after you've made it

arctic lake
#

Yeah that's what I was thinking. Thanks for your help!

misty glade
#

@flint geyser what are you trying to accomplish? you want a countdown and one that's "smart" and can be called multiple times without resetting?

arctic lake
#

๐Ÿ‘

haughty sphinx
#

Context: I'm currently working on procedural terrain generation & I'm trying to make it more varied/interesting. I'm looking into mixing different noise patterns("biomes") using a larger/softer noise function.

Question: How would one structure a system that fulfils the following requirement,

  • Allows the developer to create new noise patterns (from a set of functions, like presets) & edit them within the inspector

I have the usual parameters like number of octaves, lacunarity, gain, altitude & frequency. Will probably add vertex color to the list.

misty glade
#

I'm not sure what you mean - you already have a working terrain generator with those parameters..? Why not just expose them in the inspector with a button to regenerate the terrain..?

#

If you're looking for better noise generation, I always lean on Perlin noise, it's just.. hard to beat

haughty sphinx
# misty glade If you're looking for *better* noise generation, I always lean on Perlin noise, ...

I'm already exposing the parameters in the inspector.
What I'm looking for is a system to expose them "per noise pattern".

Say I have a few different noise functions: perlin noise, fractal noise, ridges.
I'd like to be able to dynamically create new noise patterns with those functions,
a noise pattern would then be thrown into the mix & applied only on certain areas of the terrain.

I'm not looking for better noise.

misty glade
#

Ah, sorry, I understand. I'd probably use scriptable objects, then. Basically, stuff all your data points into a SO called "NoiseTemplate" or "NoiseMap" or something. Then in your MB that generates the noise, you either select/find/specify the SO you want to use, read the values, and away you go.

#

The SO is kind of like a file that saves your templates. You can also work with them programmatically if you want

#

So, example - I have these "crew". I have a crew database SO that holds them all:

#

Each crew has it's own data points:

#

and then I have some scripts that I can get the SO I care about, get the data, etc. My use case is different than yours (i'm holding images, wave files, etc) but it's the same idea - in the SO you can put any data points you want

haughty sphinx
#

Alright. I had a slight suspicion scriptable objects was the solution. But I'm really not familiar with them, so I guess it's time to learn.
Thanks for the explanation, will have a proper read through it.

misty glade
#

Then if you wanted to make a new template, you could just right click in your hierarchy and create a new template (or copy and paste an existing one):

#

(assuming you have a line of code in your SO that adds this to the editor)

misty glade
#

they're super simple.. they're just .. permanent collections of data

haughty sphinx
#

Neat! Will have a look at it.

stiff hornet
#

I can make an example of how that would work

#

Does mean that if you want to add a completely new noise pattern function you'd need a new SO script to store it in

haughty sphinx
stiff hornet
#

it is an unusual way to use them (i use it for 2d tile custom code)

#

one sec i'll make an example

stiff hornet
# haughty sphinx An example would be much appreciated. I think I need to get a grip of SO's befor...

public class NoisePatternBase : ScriptableObject
{
    //Add whatever you need to return and any external parameters
    public abstract void NoisePattern();
}

[CreateAssetMenu(fileName = "NoisePatternOne", menuName = "ScriptableObjects/NoisePatterns/NoisePatternOne")]
public class NoisePatternOne : NoisePatternBase
{
    [SerializedField]
    private float float1;

    [SerializedField]
    private float float2;

    //Same returns and parameters as base class
    public override void NoisePattern()
    {
        //Use float1, float2 with this noise pattern
        //Create multiple types of this SO to have varying float1, float2
        //Custom noise pattern code here
    };
}

[CreateAssetMenu(fileName = "NoisePatternTwo", menuName = "ScriptableObjects/NoisePatterns/NoisePatternTwo")]
public class NoisePatternTwo : NoisePatternBase
{
    [SerializedField]
    private float float1;

    [SerializedField]
    private float float2;

    [SerializedField]
    private int int1;

    //Same returns and parameters as base class
    public override void NoisePattern()
    {
        //Use float1, float2, int1 with this noise pattern
        //Create multiple types of this SO to have varying float1, float2, int1
        //Custom noise pattern code here
    };
}
#

Then you store these SO's as NoisePatternBase in your code

#

and then call NoisePattern() and it'll get the overriden method depending on the SO used

#

So you make SO's with the custom noise pattern code and then can create assets with the different variable values for each noise pattern type

haughty sphinx
dapper cave
#

I don't recommend messagepack, it's a headache to get running. better make your own serializer

misty glade
#

Good god no

#

MessagePack is f'ing amazing.

misty glade
dapper cave
#

but yeah it seems amazing, haven't been able to get it running on unity 2021.LTS. keeps returning the same "class not registered" error

#

how did you massage it?

thin mesa
#

make sure to swap the Api compatibility level in the Player Settings, fairly certain that whatever option is set by default is the wrong one for MessagePack to work

dapper cave
#

oh hang on, user error alert!

glacial hare
#

is there anyone who knows photon pun 2 that could help me quick

glacial hare
#

kk

dapper cave
arctic lake
#

I'm not entirely sure if this is a Unity question.

If I wanted to release an update to my game for all players to have. How would I do that? Would an engine except Unity need to take care of that for me? My issue is that I may plan to update my game later, but if I give new players a new game, they'll have entirely new databases, since my game likes to keep track of each player's points, stuff they've unlocked, etc.

regal olive
#

I didnt understand what does Component.SendMessage() do ? Can someone explain it for me please?

misty glade
misty glade
#

There's really not too much fuss to it, and I have hundreds (literally) of files keyed with messagepack annotations and it's pretty much no thought whatsoever.. then I just de/serialize it with one line of code

#

"1 author 1 change" ๐Ÿ˜› it's been working for me without a lot of fussin!

misty glade
# arctic lake I'm not entirely sure if this is a Unity question. If I wanted to release an up...

You just... make a new version of the game and release it to the app store. If you're relying on local databases (ie, files or unity's libraries for storing some data points) then you'll need to identify if the user has an old version and migrate it to whatever the newest version is. You'll probably want to do that in a loop, and leaving the methods intact. IE:

while (UserVersion < CurrentVersion)
{
    if (UserVersion == 1) UpdateToVersion(2);
    else if (UserVersion == 2) UpdateToVersion(3);
    .. etc ..
}
misty glade
arctic lake
#

Thanks a bunch!

misty glade
# arctic lake Thanks a bunch!

NP. It's a hard/complex topic, for what it's worth.. If you're using multiplayer and/or a common database, versioning your data has to be done with care, and you have to ensure that your migration is also tested and bug free. It's as much of a product as your game is.

arctic lake
#

Right, makes sense

#

That'll be fun to get to later on lol

misty glade
#

Honestly though don't worry about it until much much later, IMHO. It's the kind of thing that you don't really need to even think about until you're 90% or more of your way to completing a project.. Or you'll just sort of need to build one (a set of migration scripts) along the way when you upgrade and your own dev account is out of date suddenly and you get tired of mucking in the data/json/ini/registry/database directly ๐Ÿ™‚

arctic lake
#

Dang, Ic Ic

#

Thanks again

umbral geyser
#

anyone have experience in restricting max length of a verlet rope?

#

im struggling

umbral geyser
#

i figured it out, but god am i stupid

#

I already had the solution I just forgot that I had it solved

round summit
#

https://pastebin.com/sHeRf2Mf

This code is horrendously bad if anyone wants to help me work through it and clean it up, I'm trying to develop a chat system between npcs. I'd like for one npc to be able to talk to another npc and increase or decrease friendship depending on the nature of the interaction. I commented all the code based on what I want to happen but it's just not quite working. DM me please if you're going to help me!

late stone
#

anyone know how to split a generated mesh into different sections ?

violet valve
#

In Unity, the index component is Mesh.triangles. You'll have to loop through those and remove any references to the vertices that you don't choose to keep, and these lost entries will represent the triangles that are getting chopped up.

#

I assume you're trying to bisect a mesh as to cut off a part of it.

misty glade
#

More profiling woes. When I leave my computer (or unity) for a while .. even 15 minutes.. I get this huge lag spike in areas of my game. It only occurs the first time I'm coming back to Unity, subsequent runs take no time at all.. but it's annoying. Any ideas? (This one was 32 sec)

#

36*

#

Hm.. looks like a WONTFIX unity issue ๐Ÿ˜ฆ

undone coral
misty glade
#

yeah

#

5 or 6

#

but i'm loading them async and only on demand

#

i'm on 2021.3.3 so.. i probably ought to just upgrade unity and see what happens, but... i'm afraid of change. ๐Ÿ™‚ Liberal personally, conservative technically

undone coral
#

lol

#

what IS a "PPtr"?

mortal gust
#

Hey doctorpangloss, I think you missed my poke from the other day. Totally fine either way. (:

misty glade
#

pointer to a pointer, right?

#

๐Ÿ™‚ no idea .. i'll probably just upgrade unity and see what happens

opaque sonnet
#

Nergro

#

Hola

misty glade
#

I'd like to make a button change its text color to 50% alpha if it's disabled.

My current idea is to make a script, toss it on any button/GO that has a button and text in the hierarchy, sniff the values and update them accordingly, but.. it doesn't change if the button becomes disabled/enabled later. I don't think I want to put an Update() check for this, as there's a lot of buttons in my app and it seems wasteful to be checking 50 objects every frame.

Anyone familiar with UnityEngine.UI.UIBehaviourExtensions and the Invoke methods? The docs are really light.. ๐Ÿ˜ฆ Specifically I'm wondering if this would work: https://docs.unity3d.com/Packages/com.unity.ugui@1.0/api/UnityEngine.UI.Tests.UIBehaviourExtensions.html#UnityEngine_UI_Tests_UIBehaviourExtensions_InvokeOnDisable_UnityEngine_EventSystems_UIBehaviour_

Here's my code so far: https://pastebin.com/DMMsJauX

Code review appreciated.

#

(this works but I imagine it's not scalable if I've got dozens of buttons in a screen, which some of my screens do)

sly grove
misty glade
#

My understanding was that only works for tint-swap buttons.. I'm using sprite swaps

#

(It didn't work when I used the ColorBlock.disabledColor approach)

#

Some bugfixes (make it work if disabled and on the first frame): https://pastebin.com/UtCSsRDQ

I feel like this is reasonably fine, even for ~100 buttons. ๐Ÿคทโ€โ™‚๏ธ It works so I'm probably just gonna move on to the next thing..

keen cloud
#

is there a reason why calling this method in a text asset load returns a null reference for the text asset even though this variable has the correct path?

#

ie using it like this

#

but it does work when there is a literal string with the same text as this would output inside

sage radish
undone coral
#

it probably doesn't have the right path

undone coral
#

it's clearly the wrong path...

lusty hatch
#

does anybody know if you can use transform.translate when working with rigidbody2d.velocity. I control my character with rigidbody.velocity, but I have a function that moves the character a certain X and Y using transform.translate, the only issue is, when the code for transform.translate is being ran(which will happen in update) the movement of the character starts to not really work and the character will move very slowly, any help? I am thinking it is an issue with using translate with velocity but not sure.

thin mesa
lusty hatch
#

@thin mesa hmm ok that makes sense, do you know how I could use the rigidbody to move similarly to the transform.Translate function? I tried rb.MovePosition but that didn't seem to work either because that sets it to a position instead of adding the position

thin mesa
#

you add the amount you want to move to the current position and pass that to moveposition, however you'll still be overwriting what you do with velocity so you'll want to prevent velocity from being assigned for the duration of the move.
still #๐Ÿ’ปโ”ƒcode-beginner though. if you need further help with it, then ask there and provide relevant code

trim turtle
#

Hey I want to ask if is possible to make Dedicated Server console input reader / handler.

flint geyser
#

Is there a way to stop a coroutine and then continue it from the same moment?

sly grove
#

and just set that bool false / true as you wish

flint geyser
#

I want it to be so that I can start all coroutines and then continue them from the same point

sly grove
#

coroutines don't work that way

flint geyser
#

:<

sly grove
#

not automatically anyway... You could do something with Time.deltaTime or some kind of global pause variable that all your coroutines listen to

#

ยฏ_(ใƒ„)_/ยฏ

flint geyser
#

I think I can do it with reflection

flint geyser
stark willow
#

I can send code but dont really want to summon the wrath of god doing so, so if there's a glaring issue with my approach before i send a bunch of spaghetti code pls lmk.

I haven't used classes and objects much before so forgive me if i use the wrong terminology. IK this isnt the optimal solution to a problem, but i have a text file I want to parse, and each line contains a bunch of delimiters to help with that. I made a class called dialogue that has a bunch of attributes. Then I made an array of objects, one for each line, and want to go through with parsing them so I can use them later.
Example of line to be parsed:
{2.01}[eejit](prompt:a:1)"Hi I need help"{2.02}
and the end goal is to have an object that has:

step: 2.01
speaker: eejit
prompt: true
action: true
choices: 1
text: "Hi I need help"
next step for choice 1: {2.02}
sly grove
#

Instead of making your own crazy file format and custom parser

stark willow
#

Ive never done anthing with JSON, so it wasnt on my radar but I can look into that

sly grove
#

Anyway you didn't actually ask a question

stark willow
#

well

#

unity says i'm not initializing the object to even set an attribute, and I dont know what i'm missing to do so, because from everything Ive seen online it should be initialized already

sly grove
#

Post your code and errors there

stark willow
#

got it, sorry

little minnow
#

Hello, So I struggle a lot to find empty tiles. I have a function that find the ore but I want that it can respawn after a amount of time, on the available places. I donโ€™t know if anyone can help. (I donโ€™t know if this actually is an advanced question)

regal glade
#

I'm trying to set an integer using the TMP input field, by doing this in a setter. Can this not work??

    public string FloorNr
    {
        set 
        {
            int.TryParse(value, out int result);
            floorNr = result; 
        }
    }
#

it's only getting set to 0

#

Doing simply Parse gives a Input string was not in a correct format error

upbeat path
regal glade
#

Hmm I see, I guess the On Value Changed is just a trigger

somber island
#

Pardon, I'm not sure if this is really an advanced matter, but no one has been able to assist in the other channels:

I have a 2D grid-based game with some randomly generated levels. I can spawn objects on the grid, but I want to randomly instantiate several 2x2 (grid cell) prefab objects as well, which should fit into valid patches of the cell grid (i.e. playable space, and not cut into walls).

Is there a best practice for evaluating available spaces that the object can go? I can think of many approaches to this, but my ideas all have either flaws or generate more overhead than I'd like.

For example, if I loop through the available cells, I can easily check if there's space, but then I am severely weighting the chance of instantiation towards the earlier coordinates. I want a roughly equal chance to appear at all possible positions. I could loop through and log all possible positions into a list, but that seems extremely cumbersome. I feel like there's an established method I'm overlooking. Any direction or reference would be greatly appreciated.

upbeat path
dense aspen
#

sounds better than my idea of checking a random 2x2 grid until you find a valid spot

somber island
# upbeat path I would make a List of all possible positions and then remove from the List once...

Ty for responding. This is the approach I'm currently posed to attempt. My key reservation is that I will need to still loop back through, since I can't really spawn any other objects in that time without inadvertently cutting off possible positions for the larger object. So, I'd need to do the full scan, choose the places and spawn those objects, and then a second pass to spawn the smaller objects.

upbeat path
#

I dont see why you would need 2 passes, just have a decision during the first pass large or small

somber island
#

Because if you take a 2x3 space, it presents two distinct positions for a 2x2 object, but if you decide not to use the first (for the large object), it's possible that a small object placed instead could obstruct the second, and then it wouldn't exist

#

(fixed that, was very unclear, sorry)

upbeat path
#

so what you are saying is you want to place all large objects first, correct?

dense aspen
#

sorry if this doesn't contribute:
would it be best to spawn the most space consuming objects first? in the above scenario, you'd be able to place the 2x2 object anywhere, remove those 4 blocks from the pool of valid 1x1 block locations, then go from there?

somber island
#

Right I believe you've both stated the case as I understand it

#

I want to ensure maximum options, which I think logically requires the larger objects to be fit first

upbeat path
#

then you do not need to scan the grid to place the large objects.
say you want 10 large objects, just randomly generate 10 sets of non overlapping coorinates

mortal gust
#

It's like playing tetris, if you don't place them optimally you will need to skip some objects anyway. So even if you pick the biggest first it might not ensure you placing all objects you want.

dense aspen
#

^ I was afraid of that

#

I can't think of a solution to that unless you are fine with having variable quantities of the resources

somber island
dense aspen
#

hm. the objects in question are obstacles?

#

that sounds like you must ensure at least one valid path between 2 important points

somber island
dense aspen
#

assuming you move either up down, left or right

somber island
#

thankfully, pathing is already okay, but yeah a good point. Now, I'm just looking to place the 2x2 objects in a valid position. As long as it's within the viable area, pathing will be okay.

dense aspen
#

I gotta sleep, gl

somber island
#

ty for your consideration, and goodnight!

upbeat path
somber island
upbeat path
#

good plan

obsidian glade
somber island
# obsidian glade it might sound silly but depending on the exact circumstances, e.g if you know t...

Right, in testing, this was fastest for me. However, a maximum limit on checks still needs to be put, and ultimately, this approach scales poorly to randomized scaling, if unique level layouts are used. I thought to offset that by actually checking if additional valid cells could be declared (e.g. bump a wall back a bit as needed), but that quickly becomes a very messy bit of logic.

There are some other approaches, like looping once, but declaring a random coordinate to start from, and picking the first available space. Making sure to set up the appropriate order of the loop is key, and it will likely be a rough facsimile of true random seed, but users might not notice.

#

For this size project, it still feels like the best overall approach for now will be to make two passes. It's a curious logic problem though, since it's fairly simple to pose as a question, but not intuitive for me to solve.

hexed meteor
#

I can change the values on my post processing profile via c# but they seem to bounce back to the original a few seconds afterwards, can anyone help? documentation is as usual completely lacking

hidden quail
#

hi! currently trying to solve a bug where adding to an object's eulerangles doesn't end up giving the expected result, rather snapping it back and forth between the expected value and the value of a buoyancy script.
I'm only trying to add onto the Y rotation axis to rotate an object left and right.

this is the buoyancy script;
https://pastebin.com/usMxdtxC
i've tracked down the bug to the line

transform.up = GetNormalWS(positionOS);```
changing said line to,,,
```cs
transform.rotation = Quaternion.LookRotation(transform.forward, GetNormalWS(positionOS));```
allows it to rotate on the Y axis but breaks the buoyancy's x and y rotation

and this is the line that changes the eulerangle in another script, which we're trying to make work righto now. 
```cs
boatParent.transform.eulerAngles += new Vector3(0,rotationSpeed,0);

any help is greatly appreciated in trying to figure this out.
thank you!

jolly token
hidden quail
#

and this is how it's supposed to act, only with the buoyancy script affecting it as well.

jolly token
mortal gust
#

Not sure if simplest, but can't you cross your new forward instead of setting transform.forward?

jolly token
#

Itโ€™s also not a good practice to read and set eulerAngles back. The case sounds like you want to rotate your object around local Y axis not the world Y axis like eulerAngles

mortal gust
#
            var up = GetNormalWS(positionOS);
            var right = Vector3.Cross(transform.forward, up);
            var newForward = Vector3.Cross(up, right);
            transform.rotation = Quaternion.LookRotation(newForward, up);

Like this. Not sure if order is wrong on those crosses x) Too long time ago I used em.

bright bridge
#

Anyone have knowledge working with the A* plugin? I am having a weird bug where even though the walls are classified as obstacles the character still tries to walk through them but the "path" doesn't have them doing that. I will have a picture below as an example.

hidden quail
hidden quail
jolly token
#

Anyways seems like your issue solved? or still have rotation issue?

regal olive
#

Hello, is there anyone that could help me out? I'm working on a FPS, and I'm currently working on creating the AI aiming mechanics for the game. The bullet is a projectile however, with non-zero values for its mass and drag. I'm not sure how I can script the AI to aim at the player, taking into account for the projectile having mass and drag.

#

I can go into further detail if needed.

kindred tusk
#

Oh, using actual rigidbodies... why?

#

why would you do that?

#

with drag too...

#

Mass shouldn't be an issue if you're setting the velocity initially, but drag seems hard. Seems like an awkward way to make an RTS, but if you really want to do something crazy like that I guess you'll have to do some math.

#

I guess you'll need to run a simultaneous equation between the velocity of the target and the more complicated behaviour of the projectile

mortal gust
kindred tusk
#

I guess you'd need to know how drag affects the rigidbody

#

But that's probably well defined

mortal gust
#

I think unity uses simple linear drag

regal olive
#

Drag just adds opposite force relative to the current direction of the bullet right? So if the bullet's going up, drag will pull it down, but if the bullet's going down, drag will push it up, and etc?

kindred tusk
#

Probably relative to the velocity of the bullet

regal olive
#

Yea that's what I was thinking

#

My initial thought is to use Quaterion.LookAt so the GunPivot (an empty that acts like a pivot for the gun gameobject within my ai gameobject) is lined up on the Y-axis, then do a numerical calculation using some equation, progressively rotating the GunPivot upwards every time the calculation fails.

kindred tusk
#

Does gravity act on these too?

regal olive
#

yea

mortal gust
kindred tusk
regal olive
# mortal gust Are you talking about the AI learning from failing shots?

So basically let's say that this equation that'll calculate the x-axis rotation value (which is the rotational value that rotates the gun up/down) starts with the value being 0 degress. The method would then run a while loop, simulating a bullet shot using a mathematical equation, and will stop running if the position of this simulated shot goes past the target or goes below the ground. Then the method would check if it went over or underneath the target, and would rotate GunPivot up/down accordingly. Then it'll simulate another shot. Keep this going until it hits the target or it reaches a point where it the method just rotates up then down then up then down... If the latter happens, just set GunPivot's x rotational value to a value in-between the 2 values. If the former happens though, just set the x rotational value to the value that will have the bullet hit the target.

#

My only issue is that I have no idea how to simulate the bullet

mortal gust
#

Are you sure you can't express the trajectory with a function?

regal olive
#

Yea that's what I'm trying to do

#

Because I messed around with Physics.Simulate and that ended up crashing my computer every time I start the unity editor.

mortal gust
#

Then you only input the distance and starting height, and you get your output rotation.

mortal gust
# regal olive Wait wdym?

I'm talking about writing the formula for distance with aspects of gravity and drag for your case as a mathematical function, and solving for your rotation. But I guess since you're gonna numerically compute it later with unity physics this would give some errors.

regal olive
#

I mean I tried doing it analytically (since what I'm trying to figure out is only the launch angle), but tbh I have no idea what equation I need to use to calculate that.

#

This is my thought process however

#

So I would have a Vector3 hold the value for this calculation. I set this Vector3 (lets call it BulletTrajectory) at BulletSpawn, and add the InitialVeloctiy value into this vector 3 forward for the Vector 3 can start moving. Then at each frame, I'd add a Gravity value pulling BulleTrajectory downward, and also add a Drag value pulling BulletTrajectory in the opposite direction of where BulletTrajectory's going.

#

not each frame. I meant at each iteration of the for/while loop*

mortal gust
#

I think the incorporation of drag makes the calculation very complicated. So if you don't need it (which you might not for simple bullet) I would skip it.

regal olive
#

alright

#

Since there would be no drag, I would assume that the bullet would now travel in a parabolic line now?

#

Since the only thing affecting it is gravity

hidden quail
sly grove
#

Anyone worked with version defines before?
They don't seem to be working for me ๐Ÿค”
I have the pictured version define in my asmdef, and TextMeshPro is NOT installed. Yet this code:

#if TEXTMESHPRO_1_4_1_OR_NEWER
        [SerializeField]
        TMPro.TMP_Text speed;
        [SerializeField]
        TMPro.TMP_Text localVelocity;
        [SerializeField]
        TMPro.TMP_Text velocity;
#else
        [SerializeField]
        Text speed;
        [SerializeField]
        Text localVelocity;
        [SerializeField]
        Text velocity;
#endif```
Seems to be compiling the top portion as I get:
`Assets/BetterPhysics/Runtime/Utilities/Speedometer.cs(12,9): error CS0246: The type or namespace name 'TMPro' could not be found (are you missing a using directive or an assembly reference?)`
jolly token
#

Check if the Packages/packages-lock.json contains textmeshpro

sly grove
#

Oh wait... I think I forgot a step here

#

I didn't actually add TMP as a dependency in this same asmdef

#

Do you still need that with a version define?

jolly token
sly grove
#

Hmm ok yeah that got rid of the error.

jolly token
#

And version define (if installing TMP is optional to your package)

tacit coyote
#

sort of a more abstract/high level question, but: is there any good guides or articles or something outlining what's considered best practice for the overall layout of scripts for the sake of managing game state and game logic? I'm a web developer with a handful of years experience so i have experience with like, web apps written in JavaScript but I'm having a little trouble trying to bridge my existing understanding into Unity and C#.

#

like is their some Unity & C# philosophy of design or library equivalent to React Redux?

undone coral
#

in terms of libraries, DOTween for programmatic animation and CineMachine for camera rigging come to mind. there are many high quality paid assets that, despite being made by 1 or 2 people, work really well

#

is there something in particular you wanna make?

tacit coyote
#

at the moment I've got a game idea that's planning to be like, top down grid layout management style game, inspired in part by Stardew Valley.

undone coral
#

worth reading to see what you are getting into

tacit coyote
#

I've not, will have to add that to my reading list.

undone coral
#

games like that are hard to author because kind of like CCGs they are decoupled in some places and tightly coupled in others

tacit coyote
#

probably doesn't help that i also want the game to have like incredibly mechanically deep systems and machines akin to factorio, which is going to pose an exciting challenge in optimized state management

undone coral
#

hmm

undone coral
#

have you looked at the stardew valley source?

#

unfortunately i don't think i can find a decompiled version in github before the multiplayer update

#

is your goal to have a working game?

tacit coyote
#

I've not

undone coral
#

usually people who like optimizing state management also like factorio, like making that kind of game and liking something that frankly doesn't matter that much is pretty aligned

#

so i'm not going to give you a hard time for this... misconception

#

you can go ahead and lean into it ("optimized state management") actually. but you will not have a working game for a long time

tacit coyote
#

i mean, yeah, working game is definitely the desire, but i also want to make sure it's something i can easily make progress on over time without having to tear apart systems and stuff, but mostly I'm just trying to hold in my head any kind of decent architectural plan that makes the next step to code/work on easy to figure out

undone coral
#

coupled: look at Game.cs. decoupled: well, there are a ton of components to this game

#

xna and unity are similar

tacit coyote
#

(but yeah I'm not in a rush on this particular game idea, this is a sorta baby of mine i intend to fiddle with on and off for awhile and i can crank out small less carefully designed game ideas whenever I'm in the mood to have that instead)

undone coral
#

they evolve a lot over time and have "crazy ants" architecture

#

i haven't seen factorio source specifically so it is hard to say for that game

#

dwarf fortress is a crazy ants architecture game, and stardew valley is more crazy ants than something you'd turn into a book

#

if that makes sense

tacit coyote
#

the factorio friday facts devlogs are fascinating glimpses into how Factorio is written tbh, it's a bafflingly well optimized and carefully designed game lol

#

never purloined the source code directly myself but i imagine i will at some point as i learn game dev more

undone coral
#

and it's hard to say anything authoritatively without source code. at the end of the day they can write anything they want in their devlogs. not saying that it is untrue

#

it can certainly be an opinionated architecture

#

but other than for that 1 game in its 1 engine, can something help you write another game? hard to say

#

finding that stuff appealing can help author this kind of game

#

how much it matters in terms of actual substantive execution i don't know. i think it's overstated

tacit coyote
#

we shall see i suppose ยฏ_(ใƒ„)_/ยฏ

#

anyway i feel like i have some better idea of how to bite into things now

undone coral
#

things like DOTS or Jobs or Burst or whatever... you can try to jump directly into this stuff but it will not help you make something that looks good. in fact starting with these will guarantee you will not have a working game for a long time

#

Rimworld, an indie simulator game made in unity, is highly decoupled

#

and has a crazy ants architecture

#

factorio is really idiosyncratic. i haven't played the minecraft mods that inspired it.

#

looks great in unity

#

really shows off "simulator" ideas without all the faff

wild cobalt
#

so im trying to make an interaction event on the inspector tht i can add it looks like its trying to work but it doesnt pop up

silk trench
#

you're just telling it to remove the component every other frame

#

and then add it back again

#

also you don't need the if statement inside the else statement

#

because the two conditions are opposite of each other

#

so the if statement will always be true

brisk pasture
#

yeah that code is kinda nonsense, can not think of any context where that makes sense

#

what are you trying to accomplish @wild cobalt ?

wild cobalt
#

i was trtying to get it to add an event

#

to the inspector

brisk pasture
#

then why is it also destroying one if its already there

#

also if just trying to add a requirement you need certain component, i would just use RequireComponent for that

wild cobalt
#

hmm

#

sso how would i implemnt tht just take out the other if?

silk trench
wild cobalt
#

yea ive never even heard of tht lol

brisk pasture
#

people generally learn of it before doing custom editors

#

lets you have it when you add your component it automatically adds the required component

#

and will not let you remove the required component in the editor till yours is

wild cobalt
#

oh ok so it would add whatever i put in there automatically mhm kinda broken

haughty raft
#

Hello all, I'm new here thought this was the right place to ask.
I'm looking for am advanced programmer to help me with a nested loop operation.
I've got two working iterations but I'm looking to tidy up a bit and wondered if anyone with some more advanced knowledge than myself fancied having a look and having a go at simplifying my code, what I'm looking for is extremely specific so if you like a challenge and know your stuff let's connect.

livid kraken
stuck onyx
#

for models in 3d we can use the unity overloads OnBecameVisible and OnBecameInvisible to know if a model is being rendered by the camera or not.
Is there something similar for the UI ? i have a UI panel that has a countdown and i dont want the countdown to be working when this panel is 'hidden' (Im actually not disabling it it im using CanvasGroups

#

just wondering if the MonoBehaviour can check itself if its being shown

charred lotus
haughty raft
#

I don't know how to post code in a readable manner
So here

  for(int o = 0; o < _Values.valuesBools.Length; o++)
    {
        if (!_Values.valuesBools[o])
        {
            for (int i = 0; i < _Values.valuesAmounts.Length; i++)
            {
                if (_Values.valuesAmounts[i] > 50)
                {
                    if (Physics.CheckSphere(SphereCentre.position, SphereRadius1, _player))
                    {
                        foreach (GameObject graphic in _Graphics) // for each graphic turn them off
                        {
                            //graphic.GetComponent<U10PS_DissolveOverTime>().CheckKey();
                            graphic.SetActive(false);
                            Debug.Log(graphic.name + "Turned off");
                        }

                        int r = Random.Range(0, _Graphics.Length);
                        _Values.valuesBools[o] = true;
                        GraphicChange(_Graphics[r]);  // here we set the graphic to use from the variable above;          
                        //StartCoroutine(ChooseGraphic());
                    }
                }
            }
        }
    }

I want this to instead of looping through via iteration, to loop through and select.
Then compare the selections value data and make changes based on the return.

But it's so much deeper than this simple nested loop.

I just made this to give an example of what I'm working on

obsidian glade
haughty raft
#

I'll look into inversion and guards that's a great starting point thanks

#

This is also all networked so there is a single script on each user solely as an identifier for use in the universal graphic script

obsidian glade
#

I'd think there's better architecture you could use for this problem, i.e have the user notify the universal script when a value has changed to be above 50, rather than constantly iterating and polling every value for every user

if this is working though and you'd just like to make it more readable, then it seems like you just want a small bit of refactoring to reduce nesting & extracting blocks to other methods

haughty raft
# obsidian glade I'd think there's better architecture you could use for this problem, i.e have t...

Your pretty spot on with what you've said.
It is working almost exactly as I want.
The actual code is 300 odd lines
But yes it's working as intended.
The problem with sending data to the script is I will have hundreds of them across the world.
But currently they're universal and based on a sphere check.
So they only trigger when a player is near.
What I can have is players sending data to hundreds of scripts that then do something with it if a user isn't nearby.

I may be overthinking this.
But you've given some good points to look into so than you

random dust
#

It just hurts my eyes to see the nesting

haughty raft
grizzled furnace
#

anybody know how I can turn off an ISystem from a MonoBehavior? Trying to access it only gets me a SystemHandle and I couldn't find any easy way to access it's SystemState to set it to Enabled = false

cloud crag
#

Are new strings generated every update iteration? Meaning is it bad for performance? As I think it needs to be handled by garbage collector and if it creates every string object behind the scenes every time that is not good. should I cache these strings?

grizzled furnace
limpid prairie
#

hey guys, can anyone help with this one?

given a string, lets saying "the quick brown fox jumped over the fence".

Given an index, let's say 4, retrieve the word from the string starting at that index. A 'word' is any combination of chars encased by spaces.

So it'd return "quick".

#

So far, I take the whole string, and use string.Split(" "), to get list of words, but then idk which one is the closest to the index provided in the string

#

I guess I can then use string.IndexOf(word), but that seems so rough and poorly coded

onyx blade
#

Could someone please tell me what the hell is going on with this bounding box I tried to generate... It's way too big on the right side and that makes no sense ```cs
var parentPosition = ARManager.Instance.instanceController.sceneRoot.transform.position;
var parentRotation = ARManager.Instance.instanceController.sceneRoot.transform.rotation;

    ARManager.Instance.instanceController.sceneRoot.transform.position = Vector3.zero;
    ARManager.Instance.instanceController.sceneRoot.transform.rotation = Quaternion.identity;
    
    Renderer[] renderers = target.GetComponentsInChildren<Renderer>();
    var bounds = renderers[0].bounds;
    foreach (Renderer renderer in renderers.Where(x => x.gameObject.activeInHierarchy))
    {
        bounds.Encapsulate(renderer.bounds);
    }
#

There are no hidden objects, everything is visible, I made sure to reset the rotation because that messes with the bounding box generation as well but it. just. will not. behave

blazing verge
#

Hey, my game takes place in the space, and the game has a huge scene, and I'm currently trying to add pathfinding to it. A* is prob the way to go, but taking in account that my world is huge there's no efficient way of creating a grid, so it has to be dynamic. Is there any algorithm that solves my problem, or should I find a way to make the grid dynamically generated?

narrow pier
#

how do i add ui to photon fusion?

dusty wigeon
#

@blazing verge The complexity of a pathfinding algorithm depends on the number of obstacles and not space. Also, I do not know how the A* solution of unity operates in 3D space. (The algorithm works in 3D) Personally, I would create node that would define a highway and an other algorithm for finding the path to the highway from any place.

blazing verge
dusty wigeon
#

It depends on how your environment works, but it could work in some scenario.

obsidian glade
blazing verge
#

Well, I have player's spaceship that constantly moves, and I need to add bots, that will follow the player, so the player moves themselves, and other bots move too, so I'll probably have to recalculate the grid each frame while also making it dynamic depending on position of the player, I guess

#

I just thought there was already working algorithm for that

dusty wigeon
#

Start by trying to use a lerp on the player + a teleport when to far or stuck.

#

You will probably never have obstacles between the player and the bots. You could also keep in memory the path the player took and reuse it.

#

For a follow, most of the time, there is no need for pathfinding.

undone coral
grizzled furnace
#

DOTS. trying to stop a dots system from a monobehavior

icy smelt
#

You guys ever had an issue where you referenced UnityEngine.dll from a compiled managed library, then when building the player and running a given method it complain about a given Unity.CoreModule class?

#

I'm not getting errors on the editor, but when building my application and creating a NativeArray with UnsafeUtility, I'm getting this error:

System.TypeLoadException: Could not resolve type with token 0100008b (from typeref, class/assembly Unity.Collections.LowLevel.Unsafe.AtomicSafetyHandle, UnityEngine, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null)
#

Strangely, every time I reference a UnityEngine.dll from a managed library, the version stays 0.0.0.0

sage radish
#

So you should reference UnityEngine.CoreModule instead, or whichever module has what you need.

upbeat path
icy smelt
#

In this case, UnityEngine.dll and UnityEngine.CoreModule.dll

#

I had no issues previously by using UnityEngine.dll reference, only this UnsafeUtility method is throwing errors

#

Oh, just realized the player UnityEngine.dll is different and does not have the duplicated methods

#

Lemme see if that fixes the issue

sage radish
#

Does UnityEngine.CoreModule.dll not have all the types you need?

icy smelt
#

Same error, even when referencing UnityEngine.CoreModule instead of UnityEngine.dll

#

Not happening on the editor, only on runtime

sage radish
#

Do you have any code stripping enabled?

icy smelt
#

I can't find the Collections package on my compiled app, tho

#

oof

sage radish
#

oof?

icy smelt
#

I mean, not sure what is up

rain prairie
#

what should i do if i cant tell if a problem im having is because something is broken or because the set up of my game is just poorly set up? is there anything even to do? is it okay if it just works even if in a jank way on the back end?

sage radish
icy smelt
#

Well, let me see if enabling it in my lib does something

#

Which I think it wont

sage radish
sage radish
icy smelt
#

2019.4.40f1

sage radish
icy smelt
#

Oh

sage radish
#

But I imagine ENABLE_UNITY_COLLECTIONS_CHECKS is only true in the editor

icy smelt
#

I'll have to think about how to do that since all my code is precompiled into libraries. So I can't use such conditional (unless I create duplicated methods which should take a while to implement)

#

Indeed, by removing the safety checking entirely, it works perfectly outside the editor

timber flame
#

What is the best way to use ProfilerMarker? Can I define an array of profiler marker (native array) and use it in different jobs?

icy smelt
#

Tks @sage radish

burnt egret
#

I've got an interesting question, whats your setup? What tools do you use for coding/deploying/maintaining your game? Also, as someone who didn't come from a CS background, what are some useful things I should look into when it comes to games? (For example I just started learning database stuff recently)

misty glade
compact ingot
lapis kestrel
#

can anyone help me fix this

compact ingot
#

the tools you use 10 years down the road may be useless to you while you are only 2 years into it all. You might miss on some key insights for half your career and know more about others that anyone. There is no standard toolset that suits everyone's journey/needs

compact ingot
lapis kestrel
compact ingot
plush hare
#

Does anyone here do memory alignment for faster performance?

lapis kestrel
burnt egret
#

I'm asking something more like "what's your go-to tech stack" essentially

compact ingot
# burnt egret I'm asking something more like "what's your go-to tech stack" essentially

there isn't one. particularly in games there are only very few common problems that can be solved generically, most things quickly need custom implementations. For small projects you can get away with libraries, for larger ones a library or framework often gets in the way of the design for no good reason. This is even true for big frameworks like unity/godot/ue, they arguably don't really help in making a good game (they just take care of a few things typically required by a small to medium sized, non-cutting-edge project), they provides the bare fundamentals on top of which you build your custom libraries/tools.

#

as a general strategy for a company it can make sense to build most parts themselves to give them more opportunity to build something unique, even if the particular tech isn't immediately visible, the process and mindset of it are doing the work regardless.

#

Also libraries introduce a maintenance hazard, if it isn't supported by a reliable entity, support could just go away and you're stuck with maintaining it yourself, which in the case of a generic library can be a lot of work and quite low ROI if your project doesn't need all that much generality. Often its more efficient to build the specific thing you need yourself than rely on an opulent solution that also deals with 10 other things and has a more complicated API everyone has to learn.

burnt egret
#

So dialogue is pretty common in modern games, and so are cinematics, and for those things I'd personally not want to start with scratch given cinemachine is pretty comprehensive and there's a handful of interesting solutions for dialogue you can just grab for free

#

Or like, why bother writing your own networking solution from scratch unless you're just learning how it works

#

I think regardless when you're working in a team you're gonna have to learn how to read someone else's stuff anyways, so if you had something that could fill a need of your game that has documentation + has had the time to mature into a usable tool, it's probably best suited for big problems like those. I've also just found it a tad interesting how a lot of games focus on combat and have healthbars but those aren't "out of the box" things in unity, whereas unreal has a lot more out of the box

#

And then of course there's the libraries you write yourself that are transferrable, like player controllers or damage systems or AI (which, behaviour trees are extremely useful and making one from scratch mid prod sounds like a nightmare but they aren't in unity by default)

crystal parrot
#

Can i run unity server on ARM?

#

will it ever work?

sly grove
crystal parrot
#

yeah

#

i want to host a game server on ARM (they are super cheap) servers

undone coral
sly grove
crystal parrot
#

There is no plan to support arm? 80 core arm servers costs the same as 6 core x86

sly grove
#

I didn't say there's no plan

#

I don't work at Unity, I don't know what their plans are

lilac lantern
#

Can anyone point me in the right direction? I'm trying to rotate by using quaternions, and it works fine individually for each axis, but when combined together I get this sort of movement instead of a smooth up/down left/right:

#

here is the code:

#
private void Mouse_performed(InputAction.CallbackContext context)
    {
        Vector2 delta = context.ReadValue<Vector2>();

        transform.rotation *= Quaternion.AngleAxis(delta.x, Vector3.up);
        transform.rotation *= Quaternion.AngleAxis(delta.y, transform.right);

    }```
#

again, for each of those rotations it works fine by itself. But if I do both like that, I cannot look up/down or left/right in a straight line.

sly grove
lilac lantern
#

ah it is?

sly grove
#

Yes go follow any fps tutorial

#

The camera is typically a child of the player and only rotates on the local x axis

#

Meanwhile the player itself only rotates on the y axis

lilac lantern
#

i generally do not like following tutorials. Also I find some computers/monitors get choppiness from cameras being children

austere jewel
#

more importantly I'd say is that generally you don't just apply delta directly, you accumulate it into variables and use those to construct the rotation

#

you can bypass the hole child thing fine if you do it that way, though you still have to understand how to construct rotations

random dust
#

If you can't figure out the location of the class then you're definitely just copy-pasting everything

#

Every person with a basic bit of c# knowledge would know that if a class exists in a namespace, you will need to reference the namespace

tawny bear
#

Plus the IDE even suggests it if there is applicable namespace

plush hare
#

Unsafe.As<char[], string>(ref chars) = _str;

Trying to reinterpret my string as a char[]. Basically it skips the first 2 indexes. _str[2] becomes char[0]

#

why is this happening?

#

or am I just using it wrong?

sage radish
# plush hare or am I just using it wrong?

Managed arrays are more than just raw pointers. Span is closer to what you're expecting. Assuming you're using a recent Unity version, you can do _str.AsSpan() and it will return a ReadOnlySpan<char>. That's a wrapper around the actual memory where the string is. C# strings are immutable, so it's only read only.

plush hare
#

without allocating anything new other than the initial pre-allocated byte array

sage radish
plush hare
#

Thanks

pulsar tapir
#

is there a way to read the stdout of a static lib you're using as a plugin - directly from unity?

hybrid plover
#

I have a script where I'd like to access my submeshes so I can determine which submesh I've hit with a raycast. This works fine when my model is marked as non static and read/Write is enabled. Once I enable static (more accurate is 'batching static') I get an error "not allowed to acces triangles/indices on mesh 'combines mesh(...)' isReadable is false; read/write should be enabled in import settings". But all my objects in the scene are read/write enabled. Any tips on how I can get around this? Not setting it static is not the way I'd want to go. I'm thinking of adding a script to each model and store the sub meshes along with material id on each object but there must be an alternative I'm not aware of?

autumn drift
#

I got an issue I was wondering if someone could help me with. I need a shove in the right direction. I need to build a technical prototype that allows a person to create their own 3D level via a WebGL level creator, This could be with prepared assets already in the build or (if possible) also with custom 3D models uploaded by the player.

This then needs to be "playable", aka the player needs to be able to spawn into their own level and just walk around. Any other behaviours needed I can tackle myself down the road. I then want to be able to save this level to a webserver, So I can access it from another client (think schools or museums building their own scenarios to then present in several places).

I've been trying to wrap my brain around how to do this. First I couldn't really find many good resources on how to make a 3D level editor in Unity, giving the player position and rotation tools not too unfamiliar from those in the actual Unity Editor.

Another huge thing is how to save and load the data. I've managed to get my desired result on the loading end using assetbundles, but the way I understand it there is no way for me to build assetbundles or addressables during runtime, and so I am unable to give that power to the player. In other words whatever someone makes it would eventually need a Unity developer to put the assetbundle together in Unity. This is "workable" as it lowers cost seeing how a Unity developer would only need to be hired for a day here and there to put the bundles together, but it is not the most desirable solution.

Another way I thought of doing is using json and CreatePrimitives, but this severely limits what meshes I can work with.

I also considered using the Resource folder somehow, but haven't touched it much before so not sure what the full benefits or capabilities would be. I just know it's like a compressed set of assets.

TL;DR Trying to build a WebGL 3D level editor that saves the level to a webserver which can then be loaded in from a separate WebGL client but I am stupid. Any pointers in the right direction appreciated.

covert solar
#

I am adding an Angle to my Ellipses with an angle value between -1 and 1 (which corresponds to -45 and 45 degrees) but this is only offsetting the Y value, I also need to shorten the length of the axis I am rotating to keep the ellipse the same shape. what factor would this be?

hollow sphinx
#

a more general question to unity's way of coding. Perhaps someone knows the answer.
For floating-point numeric values, most unity api methods use, well, the float-value type or another name would be single.
This gives us a good range of precision of roughly 6-9 digits.
Why doesnt unity use double?
Double has, well, double the blocked size on the heap as float does. If we call a script which has 50 blocked floats on the heap we are at 200 bytes, with double we were at 400. But double is much more precise with ~ 15-17 digits.

Is it as simple as "we dont need such a high precision so single/float is just enough and we save memory" or is there something more to it? It is not important to know, but rather a question i am just interested in. Sorry if this is the wrong channel, but since it is very specific to coding and mostly irrellevant for beginners i figured i'd ask here :)

stiff hornet
hollow sphinx
upbeat path
analog nexus
#

we are using async/await for a lot of our stuff, especially loading adressables. when pulling in some catalogs I get a frame of 2500ms, but the profiler is not very helpful with the stacktrace

#

it just shows MoveNext for the parent of JsonConvert.DeserializeObject

#

I wonder if this can be improved somehow

#

the stacktraces from Debug.Log are usually more helpful

#

seems to do some different unwinding

#

would using another synchronization context implementation help here

#

wasn't there some third party library that implemented a different task runner and some other helpers to wrap unitys own handles like AsyncOp

#

unitask?

stiff hornet
analog nexus
#

good to know, but we're on 2021.3.5

#

I'll look into it

random dust
#

Tip: don't start with Unity as your first project

versed oasis
random dust
#

Unity has its own learning curve and it's not a good starting point to learn c# as a whole

versed oasis
#

What do you suggest?

random dust
versed oasis
#

Ok

random dust
#

Console app, API, all fine

#

Just no total conversion like Unity

obsidian glade
#

I think it's fine to, but it's definitely easy to get lost in how things work due to the Unity framework/engine and how things work because of the C# language and CLR. If you're aware that there's a distinction and able to be observant and reframe your understanding of things from time to time (which you'll need regardless of where you start or what you do), you can be fine starting with it

#

when I first started with Unity I pretty much used it strictly as graphical console, with a MonoBehaviour in the scene as the app entry point and from there writing effectively a console application, slowly incorporating some Unity features to display things in the scene

versed oasis
#

I guess it depends on personal motivation. For me I found it easier to learn in unity. Was more fun and practical for me

random dust
#

For a more experienced programmer trying c# and Unity I'm sure it is easier to adapt, but you will still miss out on a lot of fundamentals of c# if you decide to start with Unity

random dust
#

That's why I'm always daying to just start with c# and get those basics down. It allows you to understand how actual c# works, and also gives you the opportunity to understand why Unity does it different

karmic surge
vocal dagger
#

Could anyone help me with preprocessor variables real quick ?

My library supports .NetStandard 2.1 and is compatible with newever unity versions.
However my libray also features c#11 API stuff like generic attributes Attribute<T...>.
Unity does only support c#8.

Can i still use the library with unity as long as i dont use the attributes ? Or what happens in that case ?
Wrapping that stuff into preprocessor variables wont help since its a nuget.

#

Any help appreciated

covert solar
#

since 0 degrees is 0 and 45 degrees is 1, I tried remapping a 0-1 scale to a scale of 1-0.70708 which seems to be the factor of how much shorter it needs to be at 45 degrees but this didn't work. maybe I remapped it wrong

sly grove
covert solar
#

it seems I am overcomplicating things... I can simply rotate the empty object I am orbiting around...

sly grove
#

Probably better to create a transformation matrix (Matrix4x4) and multiply all the points in your ellipse with that matrix to transform it

#

or that, yes

vocal dagger
karmic surge
#

it s to create a path for an object to

timber flame
#

How do you prefer to implement it?
There are different type of buildings. It does not matter, in my example, it is building but can be everything like weapon, etc.
They have same components as well as specific ones.
To create them, they need level number and definition data. Their components are initialized by definition data
For each building type, there is a corresponding definition type.
Do you favor to create factory class for each building type?
or one factory for all of them. Create method takes Int level and base definition data. Then, each building cast base definition data to specific definition inside its own class.

#

another approach
passing level and building ID instead of its definition to factory class, then getting data by id in the building classes

blissful peak
#

Hi there im trying to parse this json but I dont know what the class look like ```json
{"-NM60tD29b7Bp7E21h5v":{"guid":"8aa219ff-0111-4b9c-8c98-675ea08171cd","levelData":"banana"},"-NM61TrzwR2csc_07MMK":{"guid":"c5ab1f87-bae8-493e-ae96-39bced732c8b","levelData":"banana"},"-NM62unW9banfKbcwJ1W":{"guid":"3af2034e-d538-4c1f-89b4-4a8fadf51f02","levelData":"banana"},"-NM65Ck5Cz1PzqN3k4ex":{"guid":"ccbd9172-8f78-476c-8118-31264aad0540","levelData":"banana"}}

sly grove
#

Just looks like a Dictionary<string, SomeObject> where SomeObject contains a string guid and string levelData @blissful peak

#

Not something that can be parsed with UnityEngine.JsonUtility though

blissful peak
blissful peak
blissful peak
icy smelt
#

Do you guys know about any library/template to help migrating a codebase to use IEnumerators (so I can use Coroutines with it)?
I don't want to break compatibility with my existing code, and the way I think about doing it would require adding lots of #ifs into the code

keen cloud
keen cloud
#

@sly grove Reasonable lol Iโ€™ll say it here, I wanted to thank you for the help youโ€™ve given me over the last year. Tomorrow is my thesis proposal presentation and I absolutely would not have been at the stage Im at without your help. I appreciate it

sly grove
keen cloud
#

But yeah thanks lol

vocal granite
#

Does anyone know how to add/modify script code through editor script only for when build game (assembly) without changing project scripts?

silk trench
#

like what would this system be used for

vocal granite
silk trench
#

Why only for a build?

silk trench
#

Not really

#

but what scripts do you want to reference

#

and why only for a build

#

oh there is an alternative

#

you can use preprocessors

#

like #if UNITY_EDITOR I think

#

then #else

#

for anything else

#

but you can't inject code along the build pipeline unless you had Unity's source code and changed it to allow for that

vocal granite
#

I'll try to explain but I'm terrible at that hehe, I can reference some variables, the variables I want, through the editor side I want to remove the unused variables (because there are many) modifying the script through System.IO but only when for build, when in the editor I want to keep them in case I use them

jolly token
#

Youโ€™re right, itโ€™s terrible explanation

jolly token
plush hare
#

So if I take all of my c# framework code, compile it into a DLL, does it then become native machine code? Or is it still going to be interpreted?

plush hare
#

Thanks

#

So then how does that work with IL2CPP?

jolly token
#

IL2CPP converts IL to CPP so

plush hare
#

Ok great

proven vault
#

I have a ton of models to import (fbx files) with materials. Whenever I bring them into Unity, the smoothness value is automatically set to 60. If I want it to be 0, is there a script I can use that automatically does that for me on import, so that I don't have to extract each individual material to edit the each value manually? (I am using URP)

proven vault
#
using UnityEngine;
using UnityEditor;
using UnityEditor.AssetImporters;

public class MaterialSmoothnessPostprocessorURP : AssetPostprocessor
{
    void OnPreprocessModel()
    {
        ModelImporter modelImporter = assetImporter as ModelImporter;
        modelImporter.materialImportMode = ModelImporterMaterialImportMode.ImportViaMaterialDescription;
        modelImporter.materialName = ModelImporterMaterialName.BasedOnMaterialName;
        modelImporter.materialSearch = ModelImporterMaterialSearch.RecursiveUp;
        modelImporter.materialLocation = ModelImporterMaterialLocation.InPrefab;
    }

    void OnPreprocessMaterialDescription(MaterialDescription description, Material material, AnimationClip[] animations)
    {
        material.SetFloat(Shader.PropertyToID("Smoothness"), 0f);
    }
}

This was my best shot lol

#

Didn't work, must be doing something wrong

#

๐Ÿค”

jolly token
proven vault
#

I do get the following warning when I reimport assets now though:
Importer(FBXImporter) generated inconsistent result for asset(guid:40320499d63dd344e9a9e696a1209e8f) "Assets/Temp/Visuals/Models/FBX/room_project.fbx"

proven vault
#

lol oops, posted that in wrong chat

muted root
#

Hi everybody, I have a problem with bones of a character when I use them inside an animation, then I can't modify their position or rotation anymore through code, it's simply ignored, even if the current animation doesn't use the blendshape... Why is it not working anymore ?

#

If the bones are never used by animation, I can change them in the update method

mental hound
#

I have a very hard problem with reversing an angle in a code (https://paste.mod.gg/ghgmpjllfqvn/0), https://gyazo.com/85052e86f74ccd0d867bcaa08d8fbc92, see this gif for the issue, my character can move in the up left diagonal and the animations change properly, but when I walk in reverse, the wrong animations play in relation to the angle, i tried numerous stuff to reverse the angle direction somehow but I failed ๐Ÿ˜ฆ

#

Basically I don't need to 'reverse' the angle variable, I just need to find a way to offset the animation in the other direction somehow when walking in reverse.

#

Because otherwise the controls would be inverted.

compact ingot
livid dawn
#

Can someone give me some direction to make my player point the same direction as my camera? I have a character that will eventually be a spider, so it walks on walls and ceilings. I'm using this code to set the rotation right now. I just changed the forward to be calculated with the camera's right rather than the object's own transform. Now it works until it gets about 90 degrees then it seems to flip and points toward the camera instead of the same direction.

//Vector3 forward = Vector3.Cross(transform.right, up);
Vector3 up = transform.position - (Vector3)closestPoint;
Vector3 forward = Vector3.Cross(sd.camera.right, up);
rigidbody.MoveRotation(Quaternion.LookRotation(forward, up));
#

Perhaps I could compare the dot product of the up vector with Vector3.down and if the spider is more upside down then I flip the forward to use -camera.right instead.

#

I'll try that, but it seems like there might be a neater mathmatical way to do it.

mental hound
#

Like this

#

gotta clean it up though

livid dawn
#

My solution didn't work. It fixed one case but broke another.

mental hound
#

This is why I didn't go in 3d game making, the maths for this is a nightmare >_<

livid dawn
#

lol just rotations. I can deal with translation and scale.

#

I think I might have figured it out. I projected the camera's forward onto the same plane that I'm rotating the player on and it seems to work for every angle I've tried.

Vector3 up = transform.position - (Vector3)closestPoint;
Vector3 forward = Vector3.ProjectOnPlane(sd.camera.forward, up);
rigidbody.MoveRotation(Quaternion.LookRotation(forward, up));
#

I love it when I start typing a method name I want to use and it actually exists.

mental hound
#

https://gyazo.com/95e3571398482e32da1980e4a24d92f0 anyone have any idea how to fix this? I have the animations set to trigger based on mouse angle, but there is a specific point between the angles where it won't know exactly which angle it is (I already rounded it), I set the camera position to the player in an OnUpdate event, I also tried making it a child of the player character in the scene and nothing worked (I think it's the camera position that is doing this if I'm not wrong).

#

When the angle changes, it jumps a keyframe in the next animation set and this bug has been plagueing me for weeks, if I put the player script that handles the animation frames in a FixedUpdate, this still happens but instead of increasing the animation speed, it jitters, it may be because Unity doesn't like doing floaty movement directions.

green river
#

so... i found on a forum that in TMPro you can add padding to a mark tag like this... <mark=#ff800080 padding="-10,-10,-10,-10">... however... it's not documented anywhere, and i cant find how it works for the life of me even reading thru Tmpro in my package cache... so like.. does anyone know where to find all the "actual" like.. modifiers you can use with mark tags, or where marks are rendered in source code?

quartz stratus
#

I'm on TextMeshPro v3.0.6

tired wyvern
#

Does someone know what happens in C# memory when I do this?

public delegate float TargetInput(GameObject actor, GameObject target);

static TargetInput TI_DistanceToTarget(float maxDist) => (actor,target) => {
        var dist = (target.transform.position - actor.transform.position).magnitude;
        return Clamp(dist/maxDist);
    };  
#

Like, if I make 10 delegates with maxDist (1..10), what does that mean in terms of memory?

sage radish
tired wyvern
#

or 10 delegates all with maxDist = 1.

#

If I make 1000 delegates all with the same maxDist, will the compiler generate 1000 classes?

sage radish
#

The compiler only generates one type for this method, but replaces the method body with just creating an instance of that type.

sage radish
# tired wyvern Does someone know what happens in C# memory when I do this? ```csharp public del...

This code gets compiled into something like:

public delegate float TargetInput(GameObject actor, GameObject target);

[CompilerGenerated]
private sealed class <>c__DisplayClass1_0
{
    public float maxDist;

    internal float <TI_DistanceToTarget>b__0(GameObject actor, GameObject target)
    {
        float num = (target.transform.position - actor.transform.position).magnitude;
        return Clamp(num / maxDist);
    }
}

private static TargetInput TI_DistanceToTarget(float maxDist)
{
    <>c__DisplayClass1_0 <>c__DisplayClass1_ = new <>c__DisplayClass1_0();
    <>c__DisplayClass1_.maxDist = maxDist;
    return new TargetInput(<>c__DisplayClass1_.<TI_DistanceToTarget>b__0);
}
#

(the compiler uses characters like <> in generated types, because you're not allowed to use those characters for naming in C#, but the compiler can, so it avoids any potential conflicts with existing types)

tired wyvern
#

very cool, my slow brain is processing atm

#

is it right to say then that for every field of type TargetInput , maxDist is occupying memory in there?

sage radish
#

Here's a cleaned up version which is a little easier to read:

public delegate float TargetInput(GameObject actor, GameObject target);

[CompilerGenerated]
private sealed class DisplayClass
{
    public float maxDist;

    internal float TI_DistanceToTarget(GameObject actor, GameObject target)
    {
        float dist = (target.transform.position - actor.transform.position).magnitude;
        return Clamp(dist/maxDist);
    }
}

private static TargetInput TI_DistanceToTarget(float maxDist)
{
    var displayClass = new DisplayClass();
    displayClass.maxDist = maxDist;
    return displayClass.TI_DistanceToTarget;
}
green river
#

I canโ€™t find the source code where you could find any other undocumented keywords for Tmp

sage radish
tired wyvern
#

the return of this:

private static TargetInput TI_DistanceToTarget(float maxDist)
{
    var displayClass = new DisplayClass();
    displayClass.maxDist = maxDist;
    return displayClass.TI_DistanceToTarget;
}

what is that? a reference or value type?

sage radish
tired wyvern
#

and what about maxDist? how is that referenced?

sage radish
#

It can't really be more clear than the example I gave you. It's creating an instance of an object that has a field where the maxDist is stored. That object also has a method that references that field in its calculation. That's the method that's being returned here. The method for that specific instance that has that specific maxDist assigned to it.

#

It's a workaround because methods can't have state tied to them, but objects can. So it's creating an object to hold the state and putting the method in that object.

tired wyvern
#

Cool, I think I get it now. It (i) wraps method + maxDist in a class, (ii) returns method that in it references maxDist.

#

Every call to TI_DistanceToTarget() creates a new DisplayClass() object

#

Thx for the help ^^

regal olive
#

Does someone know why the logic isnt working in this script? I want to do the AddMoney() Function on the time based on the InputfieldValue, when the Value is low, the time should be low also and when high then high (CheckChance Function). The Problem is, that it is constantly calling the AddMoney Function after the Time has passed. I want it for example when it calculates 10 Seconds, then after 10 Seconds it is calling the AddMoney Function ONCE, then after 10 seconds again and so on

regal olive
main stump
#

i have multiplayergame with relay and lobby, problem is when trying to launch game when all in lobby with line of code "string relayCode = await TestRelay.Instance.CreateRelay();" it says NullReferenceException: Object reference not set to an instance of an object
LobbyManager.StartGame () (at Assets/LobbyTutorial/Scripts/LobbyManager.cs:385) and i have the button dragged in the right place it says in debugging that the TestRelay.Instance is null, any suggestion how to solve ?

sly grove
main stump
#

Lobbymanager

#

testRelay

#

or post in there ๐Ÿ˜„

tender hull
#

Is there a difference between:

1๏ธโƒฃ applying an acceleration to a rigidbody using ForceMode.Acceleration

2๏ธโƒฃ taking the same acceleration from 1๏ธโƒฃ, multiplying by Time.deltaTime, and applying it using ForceMode.VelocityChange

Naively, these two things seem like they'd be identical, but I don't know if the physics system splits the physics frame into smaller timeslices for stuff like collisions, drag calculation, etc. If it did the latter, than you could imagine there being a subtle but nonzero difference between the two.

sly grove
#

Likewise:

rb.AddForce(force, ForceMode.Impulse);
// is the same as
rb.AddForce(force / rb.mass, ForceMode.VelocityChange);```
#

and

rb.AddForce(force, ForceMode.Force); // which is the default mode
// is the same as
rb.AddForce((force * Time.deltaTime) / rb.mass, ForceMode.VelocityChange);```
tender hull
#

I tend to use Time.deltaTime everywhere since it gets set to Time.fixedDeltaTime when you're in the FixedUpdate cycle

sly grove
tender hull
#

Yeah, makes sense. Like if you were doing prediction and you had no idea where your code was getting called from, it's better to be explicit

vocal granite
#

What happens if multiple asset plugins use BuildPlayerWindow.RegisterBuildPlayerHandler? Will one override the other's 'RegisterBuildPlayerHandler'?

brisk pasture
#

i think they all get executed

#

i would just make test case to know for sure

#

toss some logging in see if they all get called, and see what the final options end up as

hollow quarry
#

anyone familiar with photon pun 2 here?

#

Tried to add IsMine to my player's movement script but it breaks the character. Can anyone tell why?

#

This is my movement script

#

Player stays in falling idle animation and console says this:

grave fossil
#

I think you need investigate this:
view = GetComponent<PhotonView>(); it is null in your code. so thats why everything that in code is bellow will not work. like animations and etc.

#

so your update function is not running normaly

#

so either the script does not exists on same game object as MovementCharacterController.

vocal granite
#

This just build and not call Test();, what I'm missing?

    static void Init() {
        BuildPlayerWindow.RegisterBuildPlayerHandler(
             new System.Action<BuildPlayerOptions>(buildPlayerOptions => {
                Test();
    BuildPlayerWindow.DefaultBuildMethods.BuildPlayer(buildPlayerOptions);
             }));
    }

    static void Test() {
        Debug.Log("Success");
    }
brisk pasture
#

weird syntax

#
BuildPlayerWindow.RegisterBuildPlayerHandler(options => {
        Test();
        return BuildPlayerWindow.DefaultBuildMethods.BuildPlayer(options);
});
#

also would make sure InitializeOnLoadMethod is doing what you want would log in that method as well

vocal granite
brisk pasture
#

strange, at work i have used BuildPlayerWindow.RegisterBuildPlayerHandler a few times fine

vocal granite
#

I was trying that too but it also doesn't work:

    static void Init() {
        BuildPlayerWindow.RegisterBuildPlayerHandler(Test);
    }

    static void Test(BuildPlayerOptions options) {
        Debug.Log("Success");
        BuildPlayerWindow.DefaultBuildMethods.BuildPlayer(options);
    }
brisk pasture
#
[InitializeOnLoad]
public class BuildStepRegister {
    static BuildStepRegister() {
        BuildPlayerWindow.RegisterBuildPlayerHandler(BuildBundlesAndPlayer);
    }

    private static void BuildBundlesAndPlayer(BuildPlayerOptions options) {
        BuildPlayerWindow.DefaultBuildMethods.BuildPlayer(options);
    }
}

i removed all the code that is not relevent for you so it does nothing but this is how i have always done these

vocal granite
nimble summit
steel snow
#

is there any way to convert a string field to c# code on awake for example

#

i want to use a string field to input a math equation

#

then on awake set it up as a function to use in runnable code

oblique rampart
#

I believe so

#

What do u mean a string field to c#?

steel snow
#

in the inspector

#

a field of type string

austere jewel
#

Parse the string and decompose that into a bunch of Funcs that target prebuilt methods. It's not ideal but that's your only reasonable option

steel snow
#

ah hm

#

probably not worth it then

dire solar
#

Alternatively, you can look into adding lua support for ease of scripting

livid kraken
pure igloo
#

https://www.youtube.com/playlist?list=PLDpv2FF85TOp2KpIGcrxXY1POzfYLGWIb I've been following this tutorial on Utility AI, and one thing got me confused: it does actions as scriptable objects, and puts action score and destination inside the action. In my understanding that makes every action bound to a single NPC, unless I'm missing something. Although I don't know what. I've used them for a long time, and they've always behaved this way.

velvet rock
#

So I imagine this will be easy, just wanted to talk through it first. I have a low poly object, and I have been placing prefabs along the main edges(aka the change from one side to the other is sharp/not flat). I am not super familiar how mesh data is stored(a video on this would be amazing) nor how to tell if one side of an edge is at enough of an angle from the other to know to place a prefab at the edge though I know this information is used in shaders often.

velvet rock
#

Ah(terminology miss match I guess). Vertex? The line between two dots.

spark raft
spark raft
velvet rock
spark raft
velvet rock
#

Maybe an image of what I am doing will help more. I don't know the terminology.

spark raft
velvet rock
spark raft
#

btw. the normal vector is the vector that is pointing upwards on a vertex

velvet rock
#

So I am placing those line prefabs on the sharp edges of each face. Note that I didn't place them on the internal lines of the faces as the angle(or normals between the two tris) isn't great enough and just looks like a flat surface.

velvet rock
spark raft
#

th vertecies are the 3 points

velvet rock
#

Ah a normal is just that vector off of a tri. What is the line between two vertecies called?

spark raft
#

the interpolator (a stage in the shader) blends between the normals of the vertecies, thats how you get that smooth shading

velvet rock
#

What is the up direction of the triangle?

#

or would there be a better way of determining the angle of the edge?

spark raft
spark raft
jolly token
#

Did you set the transform as boneโ€™s parent first?

#

Yes the boneโ€™s transform.parent

#

Can you show the related code?

velvet rock
undone token
#

hey everyone, I have a very strange issue, vsync is making lag in the game so I deactivated vsync from every single place possible, however after 5-10 minutes of gameplay while profiling the game, i noticed vsync turning on by itself for a few seconds making an insane lag and then turning it self off and then game runs as normal, what is going on?

undone token
jolly token
#

This looks weird, I donโ€™t see the transform itself, the one you running the bindpose code

hollow quarry
#

Tried to make the script assign the gameobject/movementcharactercontroller script automatically once the player prefab has spawned in the scene. But I'm getting a few errors here, can anyone tell me why?

hollow quarry
violet shoal
#

MovementCharacterController is not a property of GameObject. The couple of built-in convenience shorthands for components are the exception

spark raft
violet shoal
#

However this script, once fixed, is not likely to do what you want it to do.

#

HelpUI presumably sits in the scene permanently and the character controller is then spawned in later, right?

hollow quarry
#

Its basically a UI script and I just want it to automatically assign to the player prefab containing the movementcharactercontroller script once the player has been spawned...

violet shoal
#

Right. So the Start method of the UI script is run before the spawn happens.

hollow quarry
#

ye

violet shoal
#

So even if fixed, your UI script will always fail to find the player.

hollow quarry
#

Hmm

violet shoal
#

Additionally you're running an expensive search twice - throwing the first result away.

#

Generally FindWithTag should be your last resort - or an early one if you're writing Unity tutorials for some reason.

hollow quarry
#

Reason why I wanted it was because I couldn't make a proper multiplayer since two player prefabs containing the ui elements broke on of them two.

violet shoal
#

The simplest solution for this is to turn the call order around - so it matches the spawn order.

hollow quarry
#

So like even without multiplayer just 2 players in a scene broke one of em and reason was because of the components of one of them failed to assign the right scripts

#

Uh I thought this would just be adding a few lines of code especially since this isn't my script and because I'm mostly just a game designer.

violet shoal
#

Say you have a Player component attached to your spawned player object and a Game component sitting permanently in the scene. Using approximately the same methodology you could then go:

class Player 
...
private void Start ()
{
  if (FindObjecOfType<Game> () is Game game)
  {
    game.Register (this);
  }
...
#

With the Game type then implementing a Register method ofc.

#

Alternatively you can do direct assignment where-ever you're doing the player spawn.

#

Like:

...
  Player player = Instantiate (playerPrefab, position, rotation).GetComponent<Player> ();
  game.Register (player);
...
violet shoal
hollow quarry
#

Thanks a lot buddy!

#

It's actually a game that doesn't exist yet. Online functions are the majority of the game and I'm now trying to do those internal things before working on levels and stuff.

spark raft
#

Hello I have a question I would like to ask, Now this might be a stupid question but I couldn't find anything. I would like to render a specific Object to one of the cameras but not to the others, now usually I can just assign the layers but how can I achieve the same with indirect gpu instanced objects

violet shoal
violet shoal
#

It seems to be the closest to a rendering section here ๐Ÿคท

flint geyser
#

How do I make StateMachineBehaviours receivers of corresponding animation events? Just tried adding methods with the same name to the SMBehs but still get an error saying that my animation event has no receivers

nimble summit
sly grove
#

your mesh data itself is offset from its local origin

#

This will only happen if some code/script is doing it

#

or your mesh is offset

#

etc

#

it doesn't just happen

#

Also you need to just press z

#

because you probably have tool handle pivot set to Center

#

instead of Pivot

#

this thing

#

that says Center

#

Change to Pivot

sly grove
#

did you fix your tool handle position thing

#

before all this discussion

#

is it set to Pivot?

#

skinned mesh moves vertices based on bones positions

#

so maybe your bone objects are in a different place

#

it's the top level bone in the model's armature/rig

#

or whatever Transform you assign to it will represent that bone at least

high lake
#

Given an N sided dice and M dice throws, whats the fastest way I can generate an N sized array with the value of each throw:
For example, 6 sided dice thrown 3 times: [2, 1, 4]

The first obvious approach is just loop over an N sized array and randomly generate a value from 1-N, but I'm not sure if this is the fastest.

Another approach I thought of is to do it in groups. Say you have a 6 sided dice thrown 3 times, you would have 6 groups which can be represented as an array of size 6 and then distribute the number of throws, 3, into those 6 groups:

[1, 0, 2, 0, 0, 0]

So here there was 1 throw of value 1 and 2 throws of value 3. Then I can generate a final array of [1,3,3] and scramble it.

The problem is I'm not sure how to distribute the number of throws across the group such that it represents the correct distribution for fair dice throw. (where each value has equal probability to show up). I also don't know if the scrambling makes this slower or if that messes up the probability distribution either.

Technically for my use case, the scramble isn't required but if a fast method is able to do so that would be nice.

flint sage
#

You get an array of random values between 1-6 and then take a span of a random offset with N length

high lake
flint sage
#

No idea

high lake
#

im fairly sure it doesnt

#

lets say N = 100, ur first span is on average 50, second span is then on average 25 (span of left over space, 50) etc...

flint sage
#

I mean C# Span<T>

#

Which is a subsection of an array

high lake
#

?? if you are suggesting creating an array of random values between 1-6 then you didn't understand my question since that was literally the first thing i mentioned

#

Im perfoming a very large number of dice throws like 1000000 and I want to get an array of all the values. Obviously calling random 10000000 times is gonna be slow so I was wondering if there was a faster way to do it

stiff hornet
#

the job system might be good for that. Should be pretty easy to make a job to roll a dice 1000000 times parallelised

high lake
sly grove
#

maybe I'm missing something about the question

stiff hornet
#

same

high lake
sly grove
#

oh wait I think I get it

#

say you have 100 throws. You might end up with:
[21, 19, 24, 16, 20]

high lake
#

yeah exactly

sly grove
#

But then you still need to ... randomly order them somehow?

high lake
#

yeah you need to scramble

#

but the scramble might be faster than doing n random calls

sly grove
#

It seems like you'll end up doing just as much work if not more in that process

sly grove
high lake
sly grove
#

start with numThrows / numDieFaces then do +/- with standard deviations or something

#

it doesn't seem like it'd be evenly distributed

#

I guess one question is what is the actual requirement here

#

do you need them in the order they appeared

#

or do you just want to create a distribution

high lake
sly grove
#

Do you just need [21, 19, 24, 16, 20, 20] or do you need [1, 2, 6, 4, ....x1000]

sly grove
#

what are you doing with those random numbers

high lake
#

the first one was just a suggestion i had on how you could go about making the second, but obv its flawed :p

high lake
stiff hornet
#

burst and jobs is probably the fastest you can get

sly grove
high lake
high lake
sly grove
#

maybe start with even distribution: [20, 20, 20, 20, 20, 20]

#

then do n iterations of perturbations

#

e.g.:

[20, 20, 20, 20, 20, 20]
[19, 20, 20, 20, 21, 20]
[19, 20, 20, 19, 22, 20]
[19, 19, 20, 19, 22, 21]
#

like pick one group to take move from and one group to move to

#

at random

#

do that n times

#

and you'll have some kind of random distribution

#

That n could be significantly less than the number of dice it's simulating

high lake
#

yeah I see what you are trying to do

sly grove
#

but I'm not sure how big n would have to be compared to:

  • number of groups
  • number of "rolls"
    for it to be convincing
#

you can imagine if you started with:
[1000, 1000, 1000, 1000, 1000, 1000]
obviously doing ONE iteration is not enough

#

nor is two

#

but at what point does it become "convincing"? WOuld you have to do 6000 iterations?

#

If so this isn't helpful ๐Ÿ˜‰

high lake
#

yeah i got you xD

stiff hornet
#

i'm very surprised it's so fast

#

Here it is anyway (I forgot to dispose of the array at the end)

high lake
scenic forge
icy aspen
#

Is there any way to make a gameobject more transparent without changing its materials?

somber swift
icy aspen
high lake
narrow pier
#
NavMeshMovement:IsMoving () (at Assets/uMMORPG/Scripts/MovementSystems/NavMeshMovement.cs:35)
Monster:EventMoveEnd () (at Assets/uMMORPG/Scripts/Monster.cs:136)
Monster:UpdateServer_MOVING () (at Assets/uMMORPG/Scripts/Monster.cs:272)
Monster:UpdateServer () (at Assets/uMMORPG/Scripts/Monster.cs:496)
Entity:Update () (at Assets/uMMORPG/Scripts/Entity.cs:190)```
somber swift
# icy aspen welcome to code advanced my g

If thats not what you were asking, I dont know what is. Of course you can set properties of material using Material.Set(type) instead of replacing the whole material. MaterialPropertyBlocks are also an option but they do break srp batching and works only with gpu instancing. In order to change how object is rendered, you must change the material properties/the material itself. Am I completely missunderstanding what you are asking?

vapid radish
#

Hey all, popping in with a question to see if I am missing something in the documentation. Is there any easy built in function to record and export a video in game for Unity? I see a lot of tools for devs to record in editor but I am looking to, for example, record a gif for mp4 to post to social media.

burnt egret
#

hello there, another bit of linq code that i wanna trim down

 buttons.ForEach(x => x.gameObject.SetActive(false));
 buttons.Where(x => x.name.Contains("Retry") || x.name.Contains("Menu")).ToList().ForEach(x => x.gameObject.SetActive(true));

//v2
  buttons.ForEach(x => x.gameObject.SetActive(false));
  var tempButtons = buttons.Where(x => x.name.Contains("Retry") || x.name.Contains("Menu"));
  foreach (var b in tempButtons)
    b.gameObject.SetActive(true);
#

is there any way i can do this without having to convert it to a list first?
edit: i managed to do that, but i wanted it in one line for funsies, is that possible?

brisk pasture
#

i would just not do it with linq

burnt egret
#

fair assessment

brisk pasture
#

like you are looping to check a condition and set it inactive or active

#

but you can just loop all buttons, and check that condition directly and pass it into SetActive

#

item.SetActive(item.name.Contains("Retry") || item.name.Contains("Menu")) for each iteration

#
foreach(var btn in buttons) {
    btn.SetActive(btn.name.Contains("Retry") || btn.name.Contains("Menu"));
}
burnt egret
#

it seems like i like to overcomplicate these things ๐Ÿ˜… thanks for the insight

kindred wyvern
#

I'm doing manual physics updates with Physics2D.Simulate so I can add an onPostPhysicsUpdate event for special corrections in a player. However, it looks like Unity's model of the Rigidbody2D is only updated on calls to Physics2D.Simulate. Does anyone know how I can trigger a refresh without progressing time?

brisk pasture
burnt egret
kindred wyvern
compact lion
#

How can i check if an area is inaccessible in a 2d tilemap based, i thought about using A* path finding but it would not be efficient as it would check for the whole border of the area, i thought about calculating inaccessible area and saving it but then if i implement comstruction or something changes in the game the calculation needs to be done each time.

What solutions do you suggest?

neat wasp
#

hello
I am calculating with Mathf, but it is very different from the result calculated with a calculator.
I don't know where the problem is, so I would like someone to help me.

somber swift
neat wasp
somber swift
neat wasp
somber swift
#

Please dont advertise your questions on other channels, people that are interested will read that channel too

pale silo
#

sorry.. deleted the question

vocal granite
#

How much memory does eg 10,000 empty script references take? Does it have any performance impact?
Like:

Public ScriptToReference s;
/// And more 9,999...
sage radish
#

That many serialized fields will probably slow down Unity's serializer.

vocal granite
#

@sage radish
It's not even half an MB, so it doesn't affect performance basically, but it affects the editor through the Inspector because it's public? That? sorry for the beginner question

sage radish
somber swift
#

I hope you are not trying to reinvent a list using million public fields ๐Ÿ˜…

vocal granite
vocal granite