#archived-code-general

1 messages Ā· Page 179 of 1

dense rock
#

thanks man ill try it

swift falcon
#

the states changes which one is playing

leaden ice
swift falcon
#

the running one dosent play at all anymore but the rest work just fine and flip correctly

swift falcon
leaden ice
swift falcon
leaden ice
#

otherwise you're doing this:

        else
        {
            state = MovementState.idle;```
#

so it makes sense that you're not seeing the running animation

night harness
#

Wasn't sure if this goes here or in #ā†•ļøā”ƒeditor-extensions, Do I need to be in an editor and/or customeditor to use SerializedObject to grab data? (And can I only mess with this in edit mode? Or would it possibly work in runtime)

dense rock
#

Unity says "cant convert type float to AnimationCurve"

xCurve.curveMin = windDirection.x;
#

does the MinMaxCurve store 2 animationcurves?

swift falcon
green radish
#

for some reason this isnt letting me have a summary for the method

#

as far as I can tell this should all be in order

leaden ice
#

Then write the code

#

you can do it šŸ™

swift falcon
swift falcon
leaden ice
swift falcon
#

yeah

leaden ice
#

what did you come up with

#

not the code, just the logic

swift falcon
#

i just know like when you are moving right or left it should be running and when you do nothing it should be idle and thats what i was trying to do in the script where it says else and makes it idle because if its not moving it should set back to idle i thought

leaden ice
#

you're not only looking at when you're moving

#

you have an additional condition in your if statements

#

if (dirX > 0f && !m_FacingRight)

#

else if (dirX < 0f && m_FacingRight)

#

that makes sense for deciding when to flip but it doesn't make sense for deciding the animation to play

#

make sense?

swift falcon
#

i see what you mean, i assume that means i should separate the flipping and decideing when to play, ill try to figure out how to do that thanks

leaden ice
#

the "saved in another class thing" sounds vague but also not that relevant

#
  1. get a reference to it
  2. serialize it with a json serializer
  3. write the json to a file
#

yeah that's what happens when you use JsonUtility with a ScriptableObject or MonoBehaviuour

#

why are you tryingf to serialize an SO anyway

#

is there a good reason for it to be a ScriptableObject in the firs tplace?

#

everything is possible

#

use a different json serializer

#

not much to explain

#

use a different json serializer

#

for example newtonsoft JSON

green radish
#

does anyone know how to fix this so the summary will display?

cosmic rain
#

Pretty sure SOs are serializable by JsonUtility.šŸ¤”

quaint rock
#

So's work fine with JsonUtility

cosmic rain
#

It kinda sounds like you're saving several objects in one file/string.

quaint rock
#

those look like references to SO's not the so its self

cosmic rain
#

Or the references

#

You'd need to share some code if you really need help.

quaint rock
#

use jsonUtility directly on the SO its slef

#

not on something that has a field of the so type

#

either way there are better ways to do saves then SO's anyways

#

would just use regular old classes and write the data out

#

and use something better then jsonutility

stark nimbus
#

hello, I'm trying to create my own method for sorting Dictionary<string, int> by their Value, I know there are Linq methods that can make my life easier but I want to create my own method for no reason at all
this almost works correctly, but my entitiesOrdered has 211 elements when entities has exactly 300, where did I go wrong with this code?

            Dictionary<string, int> entitiesOrdered = new Dictionary<string, int>();
            KeyValuePair<string, int> highest = new KeyValuePair<string, int>(string.Empty, 0);
            for (int i = 0; i < entities.Count; i++)
            {
                KeyValuePair<string, int> current = new KeyValuePair<string, int>(string.Empty, 0);
                int index = 0;
                foreach (KeyValuePair<string, int> kvp in entities)
                {
                    if (i == index)
                    {
                        current = kvp;
                        break;
                    }
                    index++;
                }
                if (entitiesOrdered.ContainsKey(current.Key)) continue;
                else if (highest.Value == 0) highest = current;
                else if (current.Value > highest.Value) highest = current;
                if (i != (entities.Count - 1)) continue;
                entitiesOrdered.Add(highest.Key, highest.Value);
                i = (entitiesOrdered.Count - 1);
                highest = new KeyValuePair<string, int>(string.Empty, 0);
            }
#

I actually didn't look at how the Linq methods do it

stark nimbus
quaint rock
#

can just use order by

#

keep in mind you can not store the sorted result as a Dictionary

stark nimbus
#

but they are actually sorted

#

just missing about 30% of the elements

#

output2_ is the original Dictionary

cosmic rain
#

You are serializing the Save object. It only has references to the SOs.

quaint rock
#

@stark nimbus dicts have no order though

#

would just keep it simple and just use linq and ORderBy to make a list of keyvalue pairs

#

really would not have PlayerData as a SO

cosmic rain
#

Not just FromJson. ToJson too.

quaint rock
#

just a regular class

stark nimbus
#

where did I go wrong?

quaint rock
#

if player data is not a SO, its just going to be much easier to use, can just pass it to what needs it, if its a SO the only way to maintain the serilized references is to overwrite with the json data

#

also if its a regular object with a better json library like newtonsoft you get support for data types like Dictionary for saving as well

#

@stark nimbus so all you are trying to do is sort by value in decending order?

stark nimbus
#

yes

quaint rock
stark nimbus
#

I want to avoid Linq

quaint rock
#

why

#

like you could also avoid it with the regular sort provided by C#

stark nimbus
#

I just want to know why it's not adding every element from the original Dictionary lol

quaint rock
#

would take that over trying to do your own sorting

stark nimbus
#

I probably messed up counting the i or the index

#

but that's just it

#

I just can't find the error

quaint rock
#

and what type is player data and what call is doing this?

#

and is PlayerData still some sort of SO?

#

then thats the issue

#

you can FromJson a SO since it has more stuff going on and is not just pure data

#

would need FromJsonOverwrite with a existing SO instance to overwrite

#

or like i said if you want it to work this way, don't use a SO

cosmic rain
#

Ah yeah, you need to use the Overwrite version for SOs

quaint rock
#

just use a regular class with [Serializable] on it

cosmic rain
#

You wouldn't have this specific issue if Player was a plain class

quaint rock
#

ok better question, why are you using a SO for simple data like this

#

what benefit is that giving you?

cosmic rain
#

I think you should have followed some kind of saving tutorial if it's your first time implementing something like that. Would save you a lot of time and misunderstanding.

quaint rock
#

since unless you are trying to reference the object via clicking and dragging into the inspector

#

the SO will jsut make things more complicated

#

if you just want to load some json and get a object you can use on the other side regular old C# class is the way to go

cosmic rain
#

If it's immutable data, you wouldn't need to save/load it. If it's not, you shouldn't use an SO for it anyway.

quaint rock
#

generally its good to keep your save data seperate from other runtime data

cosmic rain
#

You need to separate immutable data from non immutable.

quaint rock
#

would make it a regular C# class, then just pass it and store it as a field to what ever needs that data

#

like in projects i work on, when i construct a character i just pass in the copy of the save i loaded from disc, as a depednecy of my character script

#

its a learning process, i have seen a few people if there introduction to C# and programming is unity feel they need to stick to unity types like MB and SO

#

just regular classes and structs are useful for of lot of thigns expecially when modeling the data gets more complex

dawn mauve
cosmic rain
dawn mauve
#

Between the conversation above and the conversation that happened earlier on #archived-code-advanced it’s clear to me that designing a place for an SO is kinda challenging.

It’s almost like the game dev community wants SOs to be more than what they are

quaint rock
#

many good places to use them

#

but those uses are more like assets

#

since they can reference anything from the project

dawn mauve
#

That’s clear. But is there a game system that lends itself to being defined like assets that wouldn’t be better implemented as something else?

quaint rock
#

well would not define a system as SO's but they are a useful tool

#

at work i am using them for NPC behaviour trees

#

and for loading all store assets

#

and for a bunch of custom asset types

#

very useful tool and a lot of things would be a royal pain in the butt without them

dawn mauve
quaint rock
#

but like any tool they will just cause friction if applied from the wrong use

quaint rock
#

doing this instead of SerializeReference for nodes and blackboard vars since its less fragile

cosmic rain
quaint rock
#

all of our items use SOs that have some metadata on the item, the icon and how to display it in the UI, and the prefab for instantiating it to the scene

#

well the prefab part is actually a other addressable reference

#

so that load can be deferred

dawn mauve
#

Word.

quaint rock
#

but yeah between them in graphview was pretty easy to roll my own behaviour editor

plucky karma
#

How exactly does define constraints works in asmdef? I have setup a rule where I wanted to omit a plugin if the constraint is true from player's scripting symbol table. When I made a build, I look into the executable lib folder, and I still continue to find the plugin I wanted to omit in there.

How can I omit a plugin folder based on scripting symbol? If asmdef the answer, then I don't know why it isn't exactly doing what it's suppose to do?

quaint rock
#

you just list some defines you need in the constraints

#

or can list ones you dont need with ! infront

#

also what do you mean by plugin

#

asmdef's will only effect code in there folders not already compiled stuff, or assets

young moon
#

Hello, I'm trying to make a save and load function for my Tents & Trees game. I'm using two arrays for storing the values of where the player has placed tents, so that they can save the board with the positions of the tents they placed before saving. My issue is that my save data looks correct but when I load there is a bug happening of lines of tents copying each other. Say X is tents and O is empty cells, I save a board looking like this:
X X O
O O O
X O X
But when I load it becomes this:
X X X
O O O
X X X
Not sure where I went wrong in my code, it would be nice if anyone could tell me where I'm getting it wrong: https://gist.github.com/Oshinya/eb924142038a3e0263820375bd5014b8

Gist

Tents and Trees. GitHub Gist: instantly share code, notes, and snippets.

quaint rock
#

would heavily recommend just write it to json, instead of store individual ints in individual keys of playerprefs

#

also i would be tempted to just store your width and height, then store the rest in a flat array not a 2d one, then jsut compute the index later

#

int IndexOf(int x, int y) => x + size.x * y; for example would map from a 2d coord to a 1d index to a array

young moon
#

I would prefer saving with playerprefs because I have a lot of levels and don't want to fit everything into one json file or a thousand of them. My game is very simple so playerprefs fulfills my needs. I don't understand what you mean about storing everything else as I only have width and height to keep track of (if by width and height you mean x and y).

somber nacelle
somber nacelle
# green radish anyone?

not really a unity related question, more of a question about visual studio itself. theoretically it should JustWorkā„¢ļø but you may need to restart it. if it doesn't, then i'd ask somewhere where the question is more relevant like the c# discord or microsoft support or something šŸ¤·ā€ā™‚ļø

broken light
#

does it really matter if a gameobject is at 0,0,0 and i create my mesh by setting the verts by their world position

quaint rock
#

so if it ever gets offset its easy to put back, and you can see what that offset would be

broken light
#

i guess but its one more calculation to do for thousands of vertices lol

#

since i have to subtract by transform position

#

which is a pain

cosmic rain
#

You only need to calculate the offset once per object, not for each vertex.

broken light
#

no ? if i have world positions for each vertex i have to then do wp - transform.position to get the verts localised in the mesh

#

for every vertex

quaint rock
#

well would do the InverseTransformPoint once to get the offset

#

then you can use that on each vert

#

a subtraction per vert is not going to really matter

broken light
#

it might im regenerating the mesh whenever the mouse moves

#

so it happens often

quaint rock
#

unless its a truely massive mesh you can do it per frame fine

broken light
#

define massive?

#

+1000 verts?

quaint rock
#

1k is nothing

broken light
#

i see

quaint rock
#

dont worry about it till its a problem you can measure

broken light
#

true

quaint rock
#

but also if it was removing 1 subtraction would not help that much

broken light
#

is gpu readbacks every frame a bad idea for this ?

#

i dunno the perf cost of that

#

vs getting it cpu side

quaint rock
#

then you would look at other approaches like dividing things up so its not all updating at all times

#

or maybe doing its on its own thread or compute shader

broken light
#

i had thought about compute shader but im told sending data back to cpu from gpu isnt particularly fast

quaint rock
#

if maybe even not doing it on the cpu at all depending on your needs, like it might be a job just for a vertex shader

broken light
#

if the vert shader does it then its doing it every redraw

#

so would rather avoid that

quaint rock
#

would just see if it works before getting too in your head about it

green radish
quaint rock
#

not sure what the issue would be, vertex shader depending on the task would be ultra fast, its literally meant for moving verts about

broken light
#

because its a one time job vert shader runs every time

quaint rock
#

and you said it could update everytime the mouse moves, so that is essentially per frame anyways

broken light
#

so compute shader makes more sense

#

true regarding the mouse

#

ill try both and see which one is less of a pain in the ass to expand in future

cosmic rain
#

If you don't need that data on the CPU side(for colliders for example), a vertex shader is definitely the best solution.

broken light
#

hmm

#

can buffers be pooled for gpu

#

or reused

#

without regenerating a new one ?

cosmic rain
#

The issue is not with generating buffers but reading/writing into them.

broken light
#

oh

quaint rock
#

thing is if its truely a visual only thing vertex shader is just best

cosmic rain
#

You move data between devices(RAM - VRAM). That's the expensive part.

quaint rock
#

does not matter if its every frame, its used to dealing with millions of verts per frame

broken light
#

why vertex shader and not compute though

#

id use vertex to morph pre-existing mesh

#

didnt think it would be for generating new mesh

quaint rock
#

well you never said what the purpose was

#

and you said it was a mesh

broken light
#

mesh along splines to the mouse position

quaint rock
#

so assumed you are modifying something you are rendering

cosmic rain
quaint rock
#

problem with compute is its like 2 round trips for this usecase

cosmic rain
broken light
#

yeh thats why i'd need to create buffer of the size i need each time

quaint rock
#

yeah i was assuming you are modifying existing verts

#

if the vert count changes you need to do it on the mesh level

broken light
#

yeh it would change depending how far the mouse is

quaint rock
#

really just try it

cosmic rain
broken light
#

okay

quaint rock
#

a few thosand verts is not that bad, the overhead of cpu to gpu will take more time then that

#

and you should be able to do it a few times within a frame budget

stark nimbus
# quaint rock `dict.OrderByDescending(x => x.Value).ToList();`
        Dictionary<string, int> OrderByDescending(Dictionary<string, int> dict)
        {
            Dictionary<string, int> dict2 = new Dictionary<string, int>(dict);
            Dictionary<string, int> sorted = new Dictionary<string, int>();
            for (int i = 0; i < dict.Count; i++)
            {
               KeyValuePair<string, int> highest = Highest(dict2);
               sorted.Add(highest.Key, highest.Value);
            }
            return sorted;
        }

        KeyValuePair<string, int> Highest(Dictionary<string, int> dict)
        {
            KeyValuePair<string, int> highest = new KeyValuePair<string, int>(string.Empty, 0);
            foreach (KeyValuePair<string, int> kvp in dict)
            {
                if (kvp.Value > highest.Value) highest = kvp;
            }
            dict.Remove(highest.Key);
            return highest;
        }
quaint rock
#

that will work but will be costly, much more then any of the sorting algorithms C# already has out of the box

stark nimbus
#

more than Linq?

quaint rock
#

since for each item you add you are looping the whole collection again

#

also you should confirm Dictionary actaully maintains insertion order

rain minnow
#

if you need to constantly set the order, i'd look into another collection . . .

quaint rock
#

its based on a hashmap so unless they got something else in there to help it wont maintain order

rain minnow
#

dictionary doesn't seem like the you want/need . . .

quaint rock
#

like are you ever looking things up by key?

#

since if not, would just use a list of structs

#

they can be sorted in place

#

or go even more specialized then that depending on performance needs, like a PriorityQueue

#

also how often are you needing to do this, you could also just be greatly overestimating the costs and making it more complciated then needed

stark nimbus
#

I have no reason to avoid Linq, I just wanted to do this "manually"

#

and it does keep the order

        [ConsoleCommand("sort")]
        void Sort(ConsoleSystem.Arg arg)
        {
            Dictionary<string, uint> sorted = OrderByDescending(dict);
            SendReply(arg, $"\n{JsonConvert.SerializeObject(dict)}\n{JsonConvert.SerializeObject(sorted)}");
        }

        Dictionary<string, uint> dict = new Dictionary<string, uint>
        {
            { "ten", 10 },
            { "twenty", 20 },
            { "thirty", 30 },
            { "seventy", 70 },
            { "eighty", 80 },
            { "hundred", 100 },
            { "ninety", 90 },
            { "fourty", 40 },
            { "fifty", 50 },
            { "sixty", 60 }
        };

        Dictionary<string, uint> OrderByDescending(Dictionary<string, uint> dict)
        {
            Dictionary<string, uint> dict2 = new Dictionary<string, uint>(dict);
            Dictionary<string, uint> sorted = new Dictionary<string, uint>();
            for (uint i = 0; i < dict.Count; i++)
            {
               KeyValuePair<string, uint> highest = Highest(dict2);
               sorted.Add(highest.Key, highest.Value);
            }
            return sorted;
        }

        KeyValuePair<string, uint> Highest(Dictionary<string, uint> dict)
        {
            KeyValuePair<string, uint> highest = new KeyValuePair<string, uint>(string.Empty, 0);
            foreach (KeyValuePair<string, uint> kvp in dict)
            {
                if (kvp.Value > highest.Value) highest = kvp;
            }
            dict.Remove(highest.Key);
            return highest;
        }
quaint rock
#

.net must have a extra collection in there keeping track of insertion order then, since a traditional hashmap does not, since its optmized just for quick lookups by key

green radish
#

it it possible to store multiple datatypes in the same file and make them all serializable?

#

I added another datatype but repeating the serializable line doesnt work because it says only one can exist

quaint rock
stark nimbus
green radish
#

like this

#

cant use [System.Serializable] again so currently the second one is usable but not serializable

quaint rock
quaint rock
leaden solstice
#

Who said you can’t

green radish
#

okay so apparently it randomly decided I can use it more than once, not sure what was wrong before than

quaint rock
#

i think you put it above the comment

#

then it worked when it was the line above the class

rain minnow
#

probably just placed [Serializable] in the wrong spot . . .

green radish
#

wouldnt be the first time I've messed up positioning

plucky karma
# quaint rock also what do you mean by plugin

An .so file was embedded into the game build and I would like to omit this by using scripting symbol. I found the location, but unable to find a way to apply constraints. E.g. !DEMO_EVAL_COPY

swift falcon
#

I dont wanna ping the guy n disturb him but thx for the help i finally got it working

green radish
#

Discord is giving me a null error and claiming this is an object

#

is Unity just being broken and needs a restart?

leaden ice
#

what error message are you getting

green radish
#

links to the highlited line of code

leaden ice
# green radish

ok on line 35 of Sim_Entity.cs you are trying to use a null variable

leaden ice
green radish
#

its not null, and its not an object

leaden ice
green radish
#

this is the relevant code that comes before and after that

leaden ice
#

so they are all null

#

hence Forces[i].force is the same as null.force

#

hence the error

green radish
#

so I need to set the values of each individual element without actually calling those elements?

leaden ice
#
  1. You need to assign each element of the array to an actual object if you wish to use said objects
  2. not sure what "calling those elements" means
green radish
#

elements of the array, elements 0-2

leaden ice
lean sail
#

what are you trying to do with this for loop and switch? you could just assign the values once in start

#

instead of every frame

green radish
#

its because I'd like the values to be able to change situationally

lean sail
#

Forces[0] = new(put your force here, put your target here)
Same with force[1] and [2]

leaden ice
#

not situational at all

lean sail
#

if you want it to change based on a situation, that situation should change these values

green radish
#

I'd later change the code to ask for other things and calculate the value, right now they are hardcoded

leaden ice
#
Forces = new Force[] {
  new Force {
    force = 52,
    target = Vector2.up
  },
  new Force {
    force = 0,
    target = Vector2.zero
  },
  new Force {
    force = 52 * 0.6f,
    target = Vector2.down
  }
};```
This is how i'd do what you're trying to do in the code right now^
#

and definitely not in Update

green radish
#

if I put it in Start than they only get set once and never again

leaden ice
#

that's what your code is doing right now

#

regardless you need to initialize them in Start

#

you can change them later too

#

but you need at least this in Start

#

you can also just do:

Forces = new Force[] {
  new Force(),
  new Force(),
  new Force()
};```
Or:
```cs
int count = 3;
Forces = new Force[count];
for (int i = 0; i < count; i++) Forces[i] = new Force();```
#

regardless you need to use new at some point to create these objects

green radish
#

as for why I was doing it in Update its because I want to be able to change the length to add more forces, and if the length is hardcoded at the beginning I cant do that

leaden ice
#

Lists can be resized, arrays cannot

green radish
#

but as far as I know you cant just add length to an array, your forced to recreate the array entirely to set new length

leaden ice
#

Lists you can

#

you are using an array

#

not a list

green radish
#

because it forces you to recreate it, that also entails setting the values again

lean sail
#

you really might want to experiment with this outside unity, so you can run it quickly/see the outcome

leaden ice
green radish
#

would I still have to create each member of a list or does creating a list create them?

leaden ice
#

you still have to create each member

stark nimbus
#

count2 uses Linq's OrderByDescending(x => x.Value)

green radish
#

if I do this to ensure the item being called isnt null would this work or do I still need to set the values of the item?

leaden ice
#

with a list you start with an empty list and Add them each

#

I don't really understand why you seem to be making this hard on yourself

stark nimbus
#

that's why it took half as long

#

lol

leaden ice
#

it returns a new collection

stark nimbus
#

ah

leaden ice
#

also I don't really understand what you mean by sorting a dict anyway - Dictionaries are not ordered

green radish
leaden ice
leaden ice
#

doing Forces[i] will be out of range if there is not that many elements in the list yet

green radish
#

oh wait I see the issue now

#

oops

leaden ice
#

just initialize the list at the start, e.g.

Forces = new List<Force>() {
  new Force {
    force = 52,
    target = Vector2.up
  },
  new Force {
    force = 0,
    target = Vector2.zero
  },
  new Force {
    force = 52 * 0.6f,
    target = Vector2.down
  }
};```
green radish
#

list still starts from 0 when counting items, right?

leaden ice
#

of course

stark nimbus
# leaden ice it returns a new collection

like this?

Dictionary<string, uint> dict2 = new Dictionary<string, uint>();
foreach (KeyValuePair<string, uint> kvp in dict.OrderByDescending(x => x.Value))
{
    dict2.Add(kvp.Key, kvp.Value);
}
leaden ice
#

But again

#

this doesn't do anything

#

because Dictionaries are NOT ordered

leaden ice
#

it's undocumented behavior

#

and subject to change or be different on other platforms

night harness
#

If you need an ordered dictionary is it worth just having a tuple list?

leaden ice
#

if they need to look up values by the key efficiently, a list will not be as fast

cosmic rain
#

At that point, just wrap your data in a separate class/struct.

leaden ice
#

but if they really just want an ordered list of pairs, then sure

gray mural
#

Does someone know any easy way to make everything but 1 object not clickable

#

probably not the same as not interactable

#

so here I shouldn't be able to click on anything but "Edit - Level" panel

#

anyway, it's appearance shouldn't be changed

somber nacelle
#

you could probably cheese it and use an invisible panel that covers everything but the panel you'd like to edit. or you can put the stuff that should be clickable on another layer and modify the mask on the GraphicRaycaster

gray mural
#

I see, I will probably still let the player to scroll and select orders

leaden solstice
#

The full Image component šŸ˜„

gray mural
#

so I will just have to disable levels select action

gray mural
leaden solstice
#

Normal to have a popup background Image component for that, with some alpha to dim

#

UX wise better too if you want user to focus on that popup

gray mural
#

I see, so to make everything less visible?

leaden solstice
#

Yeah showing that ā€˜these are not clickable’

gray mural
#

I see, but I don't want to make it as I am using pgAdmin for inspiration

#

they use a box shadow there

#

and it's draggable

#

and size editable

leaden solstice
#

Sure, that feels like more of dockable window style (which you can also click background)

#

But anyways, just preference

gray mural
#

yes, this one looks better, thank you both for help šŸ˜„

#

how do I disable an action not permanently?

#

do I have to use a bool?

#
public event UnityAction<OptionSelectButton, bool> onOptionSelect;

private bool onOptionSelectEnabled = true;

public void SomeMethod(OptionSelectButton foo, bool bar)
{
    if (onOptionSelectEnabled)
        // ...
}
cosmic rain
gray mural
cosmic rain
#

Well, you're calling it from somewhere. Do you not?

#

Invoking the event.

gray mural
#

yes.

#

you mean?

private void OnEnable()
{
    onOptionSelect += SelectOption;
}

private void OnDisable()
{
    onOptionSelect -= SelectOption;
}
cosmic rain
#

No. Where do you invoke the onOptionSelect?

lean sail
#

this isnt invoking the event, thats adding/removing listeners

gray mural
#
public void InvokeOptionSelect(OptionSelectButton option, bool value) => 
    onOptionSelect?.Invoke(option, value);
cosmic rain
gray mural
#

that's because I have overloads

#
public void InvokeOptionSelect(OptionSelectButton option, bool value) => 
    onOptionSelect?.Invoke(option, value);

public void InvokeOptionSelect(OptionSelectButton option) => 
    InvokeOptionSelect(option, option != currOption);

public void InvokeOptionSelect() => InvokeOptionSelect(currOption, true);
cosmic rain
#

The issue is that you're abusing anonymous methods/lambdas. So you don't have full control over them.

lean sail
#

why is this a UnityAction šŸ¤” is there a benefit to actually using them

gray mural
gray mural
cosmic rain
gray mural
#

oh, I see now

lean sail
#

i didnt see where you are adding listeners, but yea u cant exactly do what you want if you're adding these with lambda expressions

gray mural
#
public void InvokeOptionSelect(OptionSelectButton option, bool value)
{
    if (bool)
        onOptionSelect?.Invoke(option, value);
}
lean sail
#

šŸ¤” why does that 2nd parameter even exist lol, just dont call InvokeOptionSelect

gray mural
#

sometimes the value is option != currOption

lean sail
#

i must be missing some important context, but this definitely does seem overly complicated

#

or overengineered

gray mural
#

just don't wanna call the event directly in another classes

somber nacelle
#

you can't anyway. events can only be invoked by the object that owns it

gray mural
#

how can I inherit from UnityAction?
in order to make a bool like CustomUnityAction.enabled

lean sail
#

šŸ¤” what

lean sail
#

yes.

somber nacelle
#

yes, that's literally the entire point of the event keyword for a delegate

lean sail
#

You have a function to invoke the event for you, but the event can only be invoked from the object that owns it

stable osprey
#

yeah it's great for keeping scope to a minimum

elder zenith
#

is there a way to save a Transform at Awake() to reset the object to it's original position and scale? Or do i have to store the variables separately?

lean sail
#

just save the variables separately

stable osprey
#

you'd have to store them separately yup. Something fancy you could do is utilize local functions and local variable caching

Action ResetPositionsAction;
void Awake() {
  var (pos, scale) = (transform.position, transform.localScale);
  ResetPositionsAction += ResetPositions;

  void ResetPositions() { (transform.position, transform.localScale) = (pos, scale); }
}
#

-- to avoid having to store the variables as members of the class, that is

cosmic rain
lean sail
stable osprey
#

well sure! I'd rather keep scope to the minimum at all times so wouldn't do anything else than that -- except maybe a standalone class/component that was specifically written to do that

#

but in real-case scenarios would likely just do it exactly like this

lean sail
#

ah i just meant like inspector visualizations, maybe thats just me but I like to draw a bunch of gizmos around lol

#

my scene view is like a light festival sometimes

livid hemlock
#

Hello, how can i do this when i click a button on the gamepad a new player is created and it is controlled by the gamepad and if i click a button on the keyboard the same thing happens but i control it with the keyboard, i'm using new input system and it should look like in the screenshot

cosmic rain
gray mural
stable osprey
#

@gray mural on the bright side, you can create a class that wraps a delegate and has all the functionality needed to operate on it and invoke it

stable osprey
#
public class MyDelegateWrapper {
  Action myDelegate;

  public void Invoke() => myDelegate.Invoke();

  public static implicit operator MyDelegateWrapper(Action del) => new MyDelegateWrapper() { myDelegate = del; };
  public static implicit operator = (Action del) => this.myDelegate = del;
  public static implicit operator += (Action del) => this.myDelegate += del;
  public static implicit operator -= (Action del) => this.myDelegate -= del;
}
#

yup

stable osprey
#

hmm there can be more, but yeah

#
public class MyDelegateWrapper {
  Action myDelegate;

  public void Invoke() => myDelegate.Invoke();

  // operators for Action
  public static implicit operator MyDelegateWrapper(Action del) => new MyDelegateWrapper() { myDelegate = del; };
  public static implicit operator = (Action del) => this.myDelegate = del;
  public static implicit operator += (Action del) => this.myDelegate += del;
  public static implicit operator -= (Action del) => this.myDelegate -= del;

  // operators for MyDelegateWrapper
  public static implicit operator MyDelegateWrapper(MyDelegateWrapper del) => new MyDelegateWrapper() { myDelegate = del.myDelegate; };
  public static implicit operator = (MyDelegateWrapper del) => this.myDelegate = del.myDelegate;
  public static implicit operator += (MyDelegateWrapper del) => this.myDelegate += del.myDelegate;
  public static implicit operator -= (MyDelegateWrapper del) => this.myDelegate -= del.myDelegate;
}
gray mural
stable osprey
#

np šŸ™‚

#

just tried it, seems this is the best you can have to allow sugar syntax:

public class MyDelegateWrapper {
    Action myDelegate;

    public void Invoke() => myDelegate.Invoke();

    // operators for Action
    public static implicit operator MyDelegateWrapper(Action del) => new MyDelegateWrapper() { myDelegate = del };
    public static MyDelegateWrapper operator +(MyDelegateWrapper left, Action right) => left.myDelegate += right;
    public static MyDelegateWrapper operator -(MyDelegateWrapper left, Action right) => left.myDelegate -= right;

    // operators for MyDelegateWrapper
    public static MyDelegateWrapper operator +(MyDelegateWrapper left, MyDelegateWrapper right) { left.myDelegate += right.myDelegate; return left; }
    public static MyDelegateWrapper operator -(MyDelegateWrapper left, MyDelegateWrapper right) { left.myDelegate -= right.myDelegate; return left; }
}
#

I believe this is why Unity went with AddListener and RemoveListener on its custom event types instead of sticking to the standard +=, -=, and = of C#

ancient anvil
#

Hello, I am tryign to get into unity and coding. I am trying to make doodle jump like game, and I try to find a way to spawn enemies on spawned platforms, but cant seem to understand how I can acheve that. I spawn platoforms with instantiane in random x range on fixed y and z position, with another script making those platforms "fall down". And I call the method with invoke repeating with some delay to make those platofrms to not overlap. Could you help guiding me how I can get dynamically get the position of those randomly generated platofrms so then i can spawn enemies with like 20% chance on platforms, or there's an easier way doing it?

gray thunder
#

each platform prefab could have a spawn point and just create a random chance of spawning an enemy on that spawn point

rocky helm
#

So, I've been thinking for a while and am yet to find a good solution to the following problem:
I have a List<Vector2[]> where every Vector2[] contains polygon vertices on a mesh and no vertices are shared between polygons. I would need to get all the connected polygons (aka 2 or more vertices are in roughly the same place for 2 polygons) for every polygon. The current solution I have thought of would be to loop through every 2 vertices and every other 2 vertices on other polygons, aka something roughly like this:

for(int i = 0; i < polygons.Count; i++) //Where 'polygons' is List<Vector2[]>
{ 
  for(int j = i+1; j < polygons.Count; j++) //For every polygon loop through every following polygon
  {
    if(any 2 vertices of polygons[i] overlaps with any 2 vertices of polygons[j]) //This would probably require even more loops
    {
      //Add polygons[j] to connected polygons of polygons[i]
    }
  }
}

Yet, considering there are around 100 (convex) polygons, each with 3-6 vertices each, this would be pretty slow, mostly when taking into consideration that I have a demanding function happening on the same frame.

cosmic rain
#

Where do you have this data from in the first place?

rocky helm
#

Unless you want to know off of what I create it

cosmic rain
rocky helm
#

I take it from mesh data

#

kind of

cosmic rain
#

You only need to run it x times for each vertex of the new polygon times y existing polygons.

On the other hand now you need to run each polygon z times its vertices x times all other polygons y.

rocky helm
#

That would take long no?

#

Considering there are around 100 (convex) polygons, each with 3-6 vertices each.

cosmic rain
#

Well, if you're creating them all at the same time, then yes.

#

It would be the same.

rocky helm
cosmic rain
#

Then there's not much you can do imho. Just do it asynchronously over several frames if you can afford it.

rocky helm
maiden swallow
#

hi, how to fix my player hooks into the ground? i hold 'D' (move right) and it just stops after a while

#

using unity 2d, and tilemap collider 2d

rocky helm
agile elbow
#

i got a bug when i swtich from PC platform to Mobile Platform. They are like little black dots who are going up down left and right my screen
anybody know anything that would be helpful? Thanks in advance!

#

i cant find anything on internet that is related to this

#

only on mobile platform

quartz folio
agile elbow
#

Sorry to ask but how can I use it

cosmic rain
agile elbow
#

never heard of

rocky helm
cosmic rain
rocky helm
cosmic rain
#

Why?

rocky helm
#

It's like realistic glass breaking. This glass isn't pre-broken, the player can break it

rocky helm
cosmic rain
maiden swallow
#

just google it 🤯

cosmic rain
#

Just do it in the editor and cache the data.

#

Then use it for free at runtime.

rocky helm
cosmic rain
rocky helm
cosmic rain
#

That's really all you need.

#

Just cache the shards as a list of C# object having a reference to their neighbors.

rocky helm
agile elbow
#

Vertx, i found a problem at DrawTransparentObjects. How can i see what made this problem?

quartz folio
agile elbow
#

added vertx

vestal crest
#

hey is it possible to activate multiple scene at the same time? i made a loading scene and it loads mainscene and as additive it loads ui scene. but ui scene loads 3 frames later. i want them to load at the same time

dusk apex
simple egret
#

Normally you should be able to set allowSceneActivation to false on both AsyncOperations here, and once both are ready, set them to true and it should create them at the same time

#

That's how I did a "press any key to continue" prompt once

vestal crest
#

then i should make a list of async operation and when it finishes foreach i should set them allowsceneactivation?

#

i tried it it didnt load but lemme try again

simple egret
#

You just have 2 scenes, so no need for a list

#

Use 2 variables and check them both in the while loop

vestal crest
#

when i set operations allowsceneactivation to false it stopped progress. i debug progress and it is always 0

#

i think setting true to allowsceneactivation does not activate them when you set it

quaint rock
scarlet viper
#

are inspector rotation values euler angles or local euler angles?

simple egret
#

All local

#

Position, rotation, scale

quaint rock
#

as far as data goes only the local values exist, the world ones are computed on request when accessed

late lion
sweet sedge
#

Hi everyone, good day. I am sort of a newbie to Unity and I have an issue with my scene loading in an HDRP VR project. I use the "LoadSceneAsync", but I still get a 2-3 second lag in my headset before the next scene loads and I want to have a seamless transition. Please, I would appreciate any help and suggestions I can get.

This is the code for the scene change:

heady iris
#

It's only going to be so good

#

Even if you load the scene asynchronously, it has to do a bunch of synchronous work to actually start playing the scene

trim schooner
#

Try looking at sub scenes?

heady iris
#

isn't that an ECS-specific concept

sweet sedge
trim schooner
heady iris
#

right, it converts a gameobject-based scene into entities

#

using the bakers you've defined

trim schooner
#

and loads instantly - so the video I watched said

heady iris
#

i'm not sure this is relevant...

trim schooner
#

wants to load a scene without any lag..

#

sub scenes do that..

heady iris
#

The entity component system (ECS) uses subscenes instead of scenes to manage the content of your application. This is because Unity's core scene system is incompatible with ECS.

trim schooner
#

You still have scenes, you create a sub scene.. and load that

#

Seriously, it is relevant.

heady iris
#

A subscene is a reference to an authoring or entity scene. In the Unity Editor, you create a subscene to add authoring elements to. When the subscene is closed, it triggers the baking process for related entity scenes.

#

i would be very surprised if you could do anything with subscenes if you aren't making an Entities-based game

trim schooner
#

Gonna use it for my fps vehicle game driving around a city.

ancient anvil
lucid wigeon
#

How would I force initialization of a instantiated prefab? If I just assign the public vars it's easy to forget to assign some of them.

heady iris
#

The methods in UnityEngine.Assertions.Assert may be helpful here.

#

For example...

#
void Start() {
  UnityEngine.Assertions.Assert.IsNotNull(florp);
}
#

using UnityEngine.Assertions; can cut that down to Assert.IsNotNull(florp);

#

Assertions are discarded in non-development builds

#

A failed assertion will throw an error. This makes these mistakes very loud.

rain minnow
#

you can pass an argument like a struct or any variable(s) the instantiated object needs . . .

lucid wigeon
rain minnow
lucid wigeon
rain minnow
#

if the values aren't set during runtime, then you know you forget. Updating the script to initialize the object should be a quick fix . . .

#

multiple scripts? you can place code in Awake or Start to setup and initialize a script when an object is created . . .

#

you shouldn't have to call a custom method on each script, that doesn't seem like a good design . . .

lucid wigeon
#

Isn't calling Init( ... params ...) already calling a custom method on them?

rain minnow
#

yes, i'm saying you shouldn't have to call that on multiple scripts . . .

lucid wigeon
#

what if you have a animation script and audio script which are totally unrelated and have different properties but are required on the given gameobject?

#

and both of them require initialization like assigning a nearest NPC or player or something

rain minnow
#

those properties should already be set on the scripts of the prefab . . .

#

if you need to then using a controller script (mediator) would be best . . .

lucid wigeon
#

how would I assign the current scene objects to a prefab? I believe it cannot be done, only other way round

rain minnow
#

have a controller script with references to all the components on the object, then call Init on the controller script with all the parameters needed. that method can access the other scripts and assign the values (or just pass the parameters to them) . . .

lucid wigeon
#

but called Initalise()

prime sinew
#

the name of the function doesn't matter

prime sinew
#

it's basically what Random described after anyway

heady iris
lucid wigeon
#

Ok, I am using that already, I thought there might be a better option

heady iris
#

You can't really force another method to be called, or for another property to be assigned

#

you can't always prove that a method gets called

#

halting problem, etc.

rain minnow
#

the other option is to use events. all necessary components can subscribe to an event on a controller script. you can invoke the event with params and they'll run the method attached to the subscription for each component . . .

#

we'd really have to see your code and approach to determine what you're trying to assign to everything . . .

heady iris
#

I have some values that only need to be computed once per frame. So, I can just cache the value if it's used more than once per frame.

How should I invalidate this value? I could do it in Update, but other things might have used it already. I could do it in LateUpdate, but these values could get used in LateUpdate as well

I kind of want an "EarlyUpdate" message.

#

I could record the frame that the value was last computed on, I guess

#

current use-case: anything that's visible in my game has a light level. I compute this by sampling nearby light probes, which has a non-trivial cost if you do it over and over and over..

simple egret
#

Yeah that's how I would do it

heady iris
#

of course, I think I need to re-consider my "multiple sphere-casts for every part of the target's body" scheme, first...

simple egret
#

Custom setter that does nothing if the frame is less or equals to the previously recorded one, or that the value hasn't changed

heady iris
#

(the vision system tries to estimate how "obstructed" your view of the target is by doing progressively narrower spherecasts until one doesn't hit the map)

#

i might just throw that out and rely on how many body parts are visible through simple raycasts instead

rain minnow
lucid wigeon
#

I'll stick to using the Init(...) pattern. How would you distinguish at a glance which properties are to be initialized and which can be "drag and dropped" in the inspector? I am using private [SerializeField] for each dependency property to be able to see in the inspector if it was assigned or not (like [SerializeField] GameObject player;). But then if it's unassigned (None) I cannot tell if I should drag and drop it in EDIT mode or whether it will be initialized (without checking in the code).

How else can I see if properties are assigned without using [SerializeField] or debugging? Do I need to write a custom inspector for that?

If I don't use [SerializeField] then I'm in the dark because I can't even see if given dependency was initialized without debugging.

rain minnow
heady iris
#

spreading it out over several frames, notably (I want a smeared-out value anyway)

heady iris
lucid wigeon
heady iris
#

i do wish there was a way to easily display a field but gray it out

#

basically a [ReadOnly]

#

i know people have implemented that before

rain minnow
heady iris
#

things that, if they occur, mean the game is in a bogus state

#

this is distinct from something that's just unusual or exceptional (e.g. the autosave file doesn't exist)

#

they made chasing down weird Blender crashes a lot more convenient

#

in the release build, it runs until it derefs a null pointer and explodes

#

in the development build, it throws an error because an array's length is wrong

lucid wigeon
rain minnow
#

either way seems fine to me. you can set the inspector to debug mode to see private variables (if you don't use the SerializeField method) . . .

#

it'll only be null if Init isn't called anyway, so it's easy to see where the problem or bug is . . .

sweet sedge
lucid wigeon
#

I wish there was that [Readonly] attribute to easily grey out properties in the inspector but still make them visible... Tried that a bit but it didn't work for me without creating whole custom editor for each script

sweet sedge
#

What about a way of loading all the scenes in the build at the beginning but they will be inactive until you want them you want them to be active

heady iris
#

I guess you could additively load a scene and then deactivate everything in it

#

that would get some of the work out of the way

sweet sedge
leaden ice
#

Also unclear where the activation is being allowed to continue

simple egret
#

It is backwards and yes, you prevent the scene switch from happening by setting allowSceneActivation to false

rancid frost
#

How do I delete the gameobject I created when I stop playing?

rancid frost
leaden ice
rancid frost
#

optimal to create a new gameobejct everytime I wanna play audio?

#

its for UI audio, 10 second clips max

heady iris
#

just have a persistent audio source that you call PlayOneShot on

rancid frost
leaden ice
heady iris
leaden ice
#

PlayClipAtPoint doesn't require an actual audio source in the scene

rancid frost
#

I need to set the mixer, so cant use playatclip...

heady iris
leaden ice
heady iris
#

that's how I do audio in my UI

#

the menu controller has an audio source; everyone asks the menu controller to play sounds when needed

rancid frost
heady iris
#

PlayOneShot is called on a specific audio source

#

PlayClipAtPoint is not

#

all of the settings of the audio source are respected when using PlayOneShot

rancid frost
#

So, u need a persistent source either way huh

heady iris
#

as would using AudioSource.PlayClipAtPoint

rancid frost
#

I was going to create only 1, but I dont know how to destroy it when applicaiton stops playing

heady iris
#

don't bother

#

just have an AudioSource for UI sounds

rancid frost
#

roger

rancid frost
#

How do i stop this?

#

this time, Im checking if the object is in the scene...incase I forgot to add it then, I create it

#

How can I permantenty spawn a gameobject which doesnt get destroyed after play

leaden ice
#

do it in the code that calls Destroy instead.

rancid frost
#

I meant when application STOP playing...mb

rancid frost
#

I was creating the object on a OnDisable..which is called by on destroy...

#

Thanks for the help never theless my friend

#

Question now is, how to know object is being destoyed when in onDisabled method?

leaden ice
#

you don't

#

so again it's better to trigger the audio being created in the code that is destroying the thing

#

Like one example is if you have code that takes damage on an object and destroys it if the HP is < 0, you spawn the object there rather than in OnDisable/OnDestroy

worn stirrup
#

I’m trying to figure out how I can vertically or horizontally ā€œcutā€ a sprite to make it look like it’s getting crushed, bit by bit… how can I accomplish that with pixelated sprites? I’ve looked into UV editing for sprites and it seems confusing, but a simple UV shift + collider bounds shift sounds possible if sprite UVs are actually accessible like that… does anybody have experience cutting things in a cardinal direction, with collider updates?

leaden ice
leaden ice
thorn glade
#

is there a way to do "OnCollisionEnter2D" but for a specific collider and not the gameobject that the script is attached to

heady iris
#

no, but you can check the otherCollider field on the Collision2D argument

#

the naming is a bit unintuitive. collider is what hit you

#

so otherCollider is the other collider in the collision: your own collider

thorn glade
#

like

thorn glade
#

collider2d.othercollider isnt a thing

#

alr

heady iris
#

Collision2D

#

not Collider2D

indigo path
#

Hi guys! I wanted to know if it's possible to call LoadSceneAsync from a ScriptableObject, because I saw that StartCoroutine is needed and that is a method of MonoBehaviour

leaden ice
#

If you want to start a coroutine you need a MonoBehaviour to run it

indigo path
leaden ice
vague sedge
#

i reimplemented the code completely into a new custom kinematic controller and its still doing the same thing so its 100% not because it was built with the built in character controller

steady moat
#

(Or I did not understand what you were trying to do)

ashen oyster
#

I updated today lol

vague sedge
#

but it wasnt to do with the character controller just lack of understanding

abstract temple
#

Hey all, im running through the VR development pathway on unity learn, and attempting to make the functional polaroid camera.
ive gotten as far as rendering the camera and attaching it to the newly created photograph, however it outputs a blurry mess instead of an actual photo.
here is the code im currently using: https://mystb.in/ProducerGuyanaClay

ashen oyster
#

set it to 1920 and 1080

#

At these locations

abstract temple
#

oh really? i got those numbers from the example solution when i got stuck

#

this is what the output looks like. blurry mightve been the wrong choice of words

ashen oyster
#

yeah lol

ashen oyster
thick terrace
#

are you getting any errors in the log? i think ReadPixels expects both textures to have the same format so it might be failing if your render texture isn't also RGB24 (it's probably argb32?)

abstract temple
#

no errors related to the camera no

#

changing the output size didnt change anything either

thick terrace
#

The render target and the texture must use the same format, and the format must be supported on the device for both rendering and sampling.
so maybe try using an RGBA texture? or check what format your render texture actually ends up as when you ask for the default format

spark stirrup
#

Why is this code not destroying the checkpoint? It prints the correct object, so it's detecting it correctly:

 else if (other.CompareTag("Checkpoint"))
        {
            
            // Update the last checkpoint position to the current checkpoint position
            lastCheckpointPosition = other.transform.position;
            Destroy(other);
        }
        print(other);
rigid island
spark stirrup
rigid island
#

other.gameObject

spark stirrup
summer pivot
#

I've tried, maybe I just can't understand what you mean, can you explain it in words to my game instead of someone elses?

ashen oyster
#

Does the new visual studio have AI built in??

ashen oyster
#

Oh interesting

#

Who made it

rigid island
#

Its called Intellicode

tame lotus
rigid island
#

microsoft made it

ashen oyster
#

That's crazy

#

is it any good

rigid island
#

Microsoft also own github, not surprised if they shared code from github pilot

tame lotus
#

it's great

#

although it just does 1 line at a time, not whole blocks like Copilot

ashen oyster
#

I mean that's still pretty amazing I've been typing it out since 2017

#

while tabbing the hell out of intellisense ofc

rigid island
#

yea half my code I just tab and it knows what I wanted

tame lotus
#

it is pretty creepy sometimes

rigid island
#

or maybe it just tells us we're not as unique as we think when doing mundaine things like writing code lol probably had so much data of people writing the same logic

ashen oyster
#

Well it failed here lol

#

But I guess it can't read my mind so that's fine

rigid island
ashen oyster
#

wdym regular

rigid island
#

regular POCO. not monobehavior

#

maybe thats why it didn't suggest it if it's MB

#

MB don't get new()

ashen oyster
#

it's derived from monobehaviour

#

so yeah

rigid island
#

then yeah you don't use new()`

ashen oyster
#

exactly

rigid island
#

oh you're saying intellicode put that?

ashen oyster
#

Indeed

#

with it I meant intellicode not the compiler xdd

rigid island
#

yeah it doesn't know about GetComponent ig, bummer

ashen oyster
#

But then i realised i got the wrong class and now the intellicode is different

#

even though they're both monobehaviours

rigid island
#

wait actually it does suggest GetComponent for me

#

idk whats up with yours lol

abstract temple
#

thanks šŸ‘

ashen oyster
#

Epic reference mistake

#

100% of all confusion on stackoverflow

#

Woahh, was there always github stuff or am I just finding new things now because I'm looking out for it

rigid island
#

or you mean VC built in VS

woeful spire
#

Okay, I'm confused. I'm getting weird behaviour reminicent of gimbal lock - but I'm only using Quaternions.

I'm first setting a rotation based on the object's world rotation and saving it as a Quaternion.
onGrabRotation = hit.transform.rotation; (with a raycast)

I am then, in FixedUpdate, constantly updating the rotation to match the inverse of it's original rotation.
grabJoint.targetRotation = Quaternion.Inverse(onGrabRotation);

The only thing that makes all of this weird is that I'm using a component I haven't used before; the Configurable Joint.
It's only been weird shit for me so far.
If I set the desired rotation to Quaternion.Identity, it starts rotating when it's grabbed (only on the Y-axis and relative to the world space), which is very gimbal-locky.

Is this component knows to just... not have the same rotation system or some shit?

I can post all the code, but it might not be super-tidy.

heady iris
#

the configurable joint has a ton of options

#

i'm still very weak with joints myself

olive kindle
#

do yall name base concrete/abstract classes with a suffix of Base

heady iris
#

sometimes, but it's not a hard rule

#

unlike with I-prefixing for interfaces

#

Especially if the derived classes aren't going to share any part of the abstract class's name

#

for example, I have Module that's derived by systems like Vision and Hearing

heady iris
#

maybe if it was going to be ModuleBase with VisionModule and HearingModule

gray mural
#

Why do enabled and gameObject.activeSelf show true even when the parent of the gameObject is inactive? How do I check if gameObject is actually active?

heady iris
#

you want isActiveAndEnabled

gray mural
heady iris
#

oh, that'd be on a monobehaviour

#

you want gameObject.activeInHierarchy then

dawn sandal
#

Can any one help with an issue I'm having. I wanted to continue the unity coding course and when I return my license did work, so I renewed it and when I open my project and started it none of my C# scripts work any more, but they are complied.

heady iris
dawn sandal
#

They just don't do anything

heady iris
#

log something in the Start method of one of your classes

#

that should run on every copy of the component in the scene when the game starts

gray mural
heady iris
#

what does "doesn't work" mean?

#

This lets you know whether a GameObject is active in the game. That is the case if its GameObject.activeSelf property is enabled, as well as that of all its parents.

#

should be exactly what you need

gray mural
# heady iris what does "doesn't work" mean?

I have this method:

private void AddOptionSelectListener(OptionSelectButton option)
{
    print($"gameObject.activeInHierarchy: {gameObject.activeInHierarchy}; {name}");

    if (gameObject.activeInHierarchy)
        option.AddListener(() => InvokeOptionSelect(option));
}

and Awake in the same script:

private void Awake()
{
    print($"Awake - {name} - options.Count: {options.Count}");

    AddOptionSelectListeners(options); // foreach => AddOptionSelectListener
}

AddOptionSelectListeners method adds listeners to every option in options, but the multiple options are added when this method is called from another script:

public void AddSelectOption(OptionSelectButton option)
{
    options.Add(option);
    AddOptionSelectListener(option);
}
#

I can't check if the listener is added to the button already..

#

so checking if it's active should solve it, it doesn't though

heady iris
#

I don't understand. Are most of your objects made inactive before Awake runs?

#

I don't see how the third block of code fits into this.

gray mural
#

it adds a new option

foreach (string levelId in levelIds)
{
    LevelData levelData = LevelManager.instance.GetLevelData(levelId);

    if (levelData != null)
        SpawnLevelInfo(levelData); // this method adds a new option
    else
        GameUtility.DeleteLevel(levelId);
}
lean sail
gray mural
#

so you can add initial options in the inspector

#

and then add new options

heady iris
#

I still do not understand. What is the actual problem?

gray mural
#

the listener is added twice.

#

to the button

heady iris
#

are you activating the game objects later on?

#

if they were already manually registered, they will register themselves a second time when the object becomes active

gray mural
heady iris
#

in fact, AddOptionSelectListener will always succeed if it's called by Awake

#

because, by definition, the game object must be active for Awake to run

tiny orbit
#

When I debug.log(screen.height) it prints 1,000 but its actually about 2,000. I have a few canvases that are screen space - camera which have a height of 2,000 and when I set objects height to 2,000 it fills the whole screen. Can anyone explain this discrepancy?

heady iris
#

If so, any of the Aspect options will be at half-res

delicate zinc
#

whats the easiest way to do a CapsuleCast from a CharacterController's Capsule?

Currently i have this code for it https://hastebin.com/share/bayipedesu.csharp, however, i dont precisely like how despite the rays that represent the point1 and point2 of the capsuleCast clearly dont touch the top block, it still detects a collision and draws a blue ray of the collision's normal. am i doing something wrong with how i'm calculating P1 and P2?

tiny orbit
heady iris
#

the checkbox is only active (and relevant) on higher DPI screens

hidden flicker
#

When is there even an advantage to using Update over FixedUpdate?

heady iris
#

moving the camera in FixedUpdate would be awful

tiny orbit
hidden flicker
heady iris
hidden flicker
#

fixedupdate always seems more precise

heady iris
#

imagine if you had a visual effect that only updated 50 times per second, even though your game was running at 110 FPS

#

it'd appear to be stuttering

#

FixedUpdate is used for physics so that they behave reliably.

#

but many things aren't so sensitive to the update rate

tiny orbit
hidden flicker
gray mural
#

but I don't know the best way how to do it

#

checking if the gameObject is active to add a listener (that means Awake was already called called) sounded like a normal approach

#

something went wrong though.

tiny orbit
heady iris
#

or once false and once true

gray mural
#

now I have realised why it's so

heady iris
#

it's adding option to options twice

#

that's not conditional

gray mural
#

it works when GameObject is disabled in the inspector at the start

heady iris
heady iris
gray mural
#

when it is enabled in the inspector, Awake is called for 0 options and then it's disabled in Start in another script, then options are added when activeInHierarachy is false, so no listeners are added to buttons

gray mural
#

probably my approach isn't the best

#

or the full logic with adding listeners is just too bad

#

so it's time for stupid ideas..

#

fixed:

private bool optionSelectListenersAdded = false;

private void Awake()
{
    optionSelectListenersAdded = true;

    AddOptionSelectListeners(options);
}
if (optionSelectListenersAdded)
    option.AddListener(() => InvokeOptionSelect(option));

and thanks for your help šŸ˜„

woeful spire
lean sail
#

my player is made up of 14 of those configurable joints

brisk reef
#

I'd guess it's because some of the projectiles dont get resetted properly

#

any ideas why?

summer pivot
#

I'm having an issue where when the player kills zombie while getting hit by it, the health doesnt regenerate, I had this issue where the effects still played for the same issue, however I fixed that and I thought the health regenerate would fix with it. Let me also just send scripts quickly, 3 of them link together

leaden ice
heady iris
#

yes, StopCoroutine needs to be given the value returned by StartCoroutine

#

it seems very weird for EnemyTouch to be detecting collisions with the player and then messing with the player's health regen

leaden ice
#

or the IEnumerator value returned by invoking the coroutine itself (the same instance that's passed into StartCoroutine originally)

heady iris
#

surely there could be multiple enemies

summer pivot
leaden ice
#

that's the issue

#

the coroutine dies when the zombie does

#

Why does the zombie have a script that is managing the player's health?

#

That seems backwards

summer pivot
#

So I should just put regen health and lose health in player controller script?

leaden ice
#

yes

summer pivot
#

Mate ngl I dont know what I do most of the time

leaden ice
#

basically the zombie script can just tell the player about the collision by calling a function on the player script

#

the player script should take it from there (e.g. starting/stopping coroutines etc)

heady iris
#

precisely.

#

the zombie should not care about the intricacies of the player's health regen

tall pewter
#

Hello everyone, I am using the new Unity input system, I am using it in the following way:

Where I need to use the input system I simply add the Player Input component, in the Behavior property I have it as send message and inside my character movement script I access the events that I have configured as OnMove, OnJump etc...

My problem is that I have a separate configuration script for the weapon but I realize that I am repeating the same steps of adding the component and accessing the action methods. I want to be able to have my configuration in a global way to be able to access it from any script of any prefab that needs it or if there is any convention or good practice of unity to handle the input system more efficiently.

heady iris
#

it would reference the player and forward all of the events to them

leaden ice
heady iris
#

alternatively, just stick it on the actual player, and then have the player tell the weapons about the input events

#

InputActionReferences are lovely

leaden ice
#

I actually think that having a weapon script handle input is not the best approach. Generally you'd have some controller script on the player handle the input and if there's a weapon attached it might call a "Use", "activate" or "Fire" method on the weapon script (when a weapon is equipped)

tall pewter
#

Maybe use the singleton pattern you think is correct? That way I can communicate to everyone what is happening with the entry system, it is what is occurring to me based on what they are telling me

leaden ice
#

If you want a "globally accessible state" kind of pattern, yes that's basically a singleton

heady iris
#

the player tells the weapon to fire

#

I've game-jammed several first person shooters (or vaguely similar games) and that's always what I do

#

then you can do funny stuff

#

like stapling a waepon to the wall and just making it fire on a timer

#

separation of concerns!

tall pewter
#

Ok I understand, so what I really have to do is that the player is in charge of controlling any action that happens with the weapons or if he is in a vehicle or on a plane, is that correct?

heady iris
#

Yep. You might have separate input actions for vehicles, but the vehicles still doesn't directly talk to the input system

summer pivot
tall pewter
#

Thanks

leaden ice
#

Hoenstly these coroutines are overcomplicated I think

#

as mentioned you're not really handling the StopCoroutine bit properly anyway - and you're also not really handling what happens when multiple enemies touch you at once.

#

Anyway I have stuff to do so see ya and good luck šŸ‘‹

#

should really just handle the damage and health regen either in Update or in a single long-running coroutine that you start one time in Start. Just use the isTouchingEnemy variable as needed

#

handling the lifecycle of all these different coroutines is a mess

heady iris
#

Coroutines make it really easy to get confused

#

especially when they're being run by entities with no business running them (zombies doing your health regen!)

leaden ice
#

just make a named custom struct instead of using tuple

#

Lists work fine with JsonUtility, yes

#

you cannot use tuple

#

if you have a custom class or struct, yes you must mark it as Serializable if you want JsonUtility to serialize it

swift falcon
#

I got a maybe simple question for Math-lovers.
I got a joystick that does simple input for a game.
The question is, i want to get the direction of that input.
I tried it but failed sadly. I will be happy if you give me a path on "how to do"

ashen yoke
#

do you have some code that failed?

#

its hard to imagine where it can fail

upbeat hare
#

Visual Coding With PlayMaker Cuz why not

swift falcon
# ashen yoke its hard to imagine where it can fail

yes lmao i am tried to do this by Vector2.Angle(); and it was returning weird number that i dont really believed its an angle.
I tried Quetarnion.FromToRotation(); and it seems it works but i didnt know how will i get the actual rotation like "its 45 not "01, 545,454,545" "

ashen yoke
#

ok step back , what is the direction that you need?

#

a direction vector?

#

what do you want to get in the end

swift falcon
#

I tried to explain that by visualizing but eh

#

Getting the angle between real handle position to that handle position by radial 0-360 would be enough for me i think can do the rest.

#

Could you tell me why it doesnt give me zero when i point at the top?

ashen yoke
#

i have a suspicion you didnt swap z and y

swift falcon
ashen yoke
#

the code where you extract both vectors

vestal crest
#

hey here i load main scene and additive scene to that scene. i want all of them to load exact same frame but without pressing any key. instead of pressing space i want to load all of them when im sure they are all loaded. how can i do this?

ashen yoke
#

movement and ui

wanton edge
#

Question, for choosing game levels, does anyone have a good system other than hardcoding the level name + description and then loading a save of the level compleation?

vestal crest
ashen yoke
wanton edge
ashen yoke
#

the "hardcoding" part simply comes from lack of references

ashen yoke
heady iris
#

this was asked about yesterday

wanton edge
wanton edge
#

He should have one scene and load and pool the scene data he want's to use.

#

He's already loading everyting with what he's trying to do currently.

ashen yoke
#

little need for scenes huh

wanton edge
ashen yoke
#

ive seen this before

#

you want to sit for hours debugging json files for issues, having to build up all toolchain yourself, mod support, any QOL or tech features like lightmapping go out the window, desktop only

#

anyway

wanton edge
ashen yoke
heady iris
#

well, "there's very little need for 'scenes' these days" sounds relevant here.

wanton edge
#

He's trying to do the literal opposite of what scenes offer.

ashen yoke
#

you are thinking in terms of data loaded, you ignore the fact what scene offers as means of project organization and content creation pipelines

wanton edge
#

Just pool and use what you need, it's not complicated.

wanton edge
ashen yoke
#

it is very common for large games to utilize massive amounts of scenes that are segmenting a single open world, for example

wanton edge
#

I want to organize scenes and then use all of them at once

ashen yoke
#

yes

vagrant blade
#

Which is normal for complex projects

ashen yoke
#

thats how it works, a lot of times

vestal crest
#

actually im not loading all scenes. i want to load specific scenes at the start of the games. like UI scene MainScene

wanton edge
#

Sure mate, you are 100% correct, answer his question.

ashen yoke
#

hm

heady iris
wanton edge
#

Complex project

vestal crest
#

why wouldnt be?

wanton edge
vestal crest
#

I dont have a problem with being seperated.

wanton edge
#

But why?

#

You're just adding complexity and then trying to merge scenes UI and Gameplay.

quaint rock
#

really UI would just use nested prefabs

#

that way its just in the scene already, but is easy to work on in isolation as needed

#

before nested prefabs i used to alway do it in addative scenes

vestal crest
#

its more organized to me but it doesnt matter i used one scene till now. now i am learning to work with multiple scenes. Dont focus on UI. think something else

quaint rock
#

but that was more for workflow reasons with mulitple team members

wanton edge
quaint rock
#

if you want do UI with scenes, just learn about addative scene loading

#

and find a way to make the references required after

ashen yoke
vestal crest
#

my question is about additive scenes

#

you can see it from above

vagrant blade
#

Prefab or scene, it's just a container for something. Using a scene means you don't have to include your UI prefabs in each other scene at least.

ashen yoke
#

scenes for ui is a hinderance, prefab will already open the ui for editing in a separate stage, scene will force you to locate and open it every time you want to make ui adjustments, on top of that you dont have the built in means to reference that ui, create variants of it, nest it into another prefab if needed

vestal crest
#

i think both ways are okay. you dont need to put your ui prefab to other scenes you can just load the scene.

wanton edge
# vestal crest if mainsceneoperations progress is completed is it sure to other all async op is...

Mate you have multiple people suggesting to do it a different way, you're just being stubborn.

UI's are perfectly fine as prefabs and they save you the trouble of having to add extra logic around your code to wrap around scenes.

You can do what you want but it's a classic case of an XY problem https://en.wikipedia.org/wiki/XY_problem

The XY problem is a communication problem encountered in help desk, technical support, software engineering, or customer service situations where the question is about an end user's attempted solution (Y) rather than the root problem itself (X).The XY problem obscures the real issues and may even introduce secondary problems that lead to miscomm...

#

Why deal with async when you can literally just .SetActive()

#

Less complex code is always better.

ashen yoke
thick terrace
wanton edge
#

On top of loading in a scene you also have to grab all your references in that scene and set up all your events.

vestal crest
#

im not being stubborn as i said bot ways are okay to me. i dont have problem with your solution

vestal crest
#

it never works that if block

quaint rock
#

also the addative approach has a upside for systems that outlive your levels or how ever your structure the game

#

it depends on what needs are

thick terrace
vestal crest
#

here i check all ops progres

#

activation if block doesnt work

thick terrace
#

what do you mean doesn't work?

vestal crest
#

it doesnt return true

ashen yoke
#

if isDone is true on that frame, the loop will not run

#

so if the progress snaps to end in a frame, it wont be called

vestal crest
#

isdone cant be true because allsceneactivation is false

#

mainsceneprogress is 0.9f. mainsceneprogress if works but additivescenesprogress if doesnt work

quaint rock
#

why are you doing the allow scene activation thing

#

would just let it happen by defualt, if its just UI this is going to be a very fast load

#

might even happen in 1 frames time

vestal crest
#

because i want to activate the scene if all scenes are loaded

#

actually it loads 3 frames later

ashen yoke
#

whats the progress value in the debugger?

quaint rock
#

often the scene activation is the longest part unless its a very asset heavy scene

vestal crest
quaint rock
#

since the scene activation is where its running all of the Awake, Start and OnEnables in that scene

ashen yoke
#

any errors? scene added to build index?

vestal crest
#

no errors

#

maybe the way i think is wrong i dont know. i want to activate mainscene if additive scenes are done

#

but because of allowsceneactivation, isdone does not return true

#

even if i somehow manage to activate mainscene after all additive scenes are loaded. is it sure to gameobjects in these scenes will work at the same frame. lets say a gameobject in MainScene and a gameobject in UI. their awake will work at the time.framecount?

ashen yoke
#

where is the coroutine called from?

#

from a DDOL object?

#

is it actually looping?

vestal crest
#

nope a gameobject in loadingscreen

#

at start

ashen yoke
#

what is loadingscreen

vestal crest
#

even if i work with input.getkeydown it doesnt work their awake at the same frame

#

a scene that has a loading bar

#

and starts game by loading mainscene and needed additive scenes

#

i guess the problem is when you load scenes as i do. scenes wont init at the same frame right? i put a gameobject in both scene and call an awake that debugs time.framecount and the results are different

quaint rock
#

your main scene you are not loading addative

#

so the thing running this logic is getting unloaded whole the coroutine is running

#

thus it stalls since its not longer ticked along

ashen yoke
#

it should load in background

#

while the coroutine is running, the issue may be that single mode and additive mode must be piped

quaint rock
#

what ever started this coroutine you need to ensure it does not get unloaded with the main scene load

thick terrace
#

trying it myself and i'm seeing the same thing, the additive operation won't go past 0 until the main one is activated, so i guess additive operations don't load until the main scene transition is done?

vestal crest
#

it unloads when main scene is activated

quaint rock
#

no but this function loads what you call the main scene, but htis function is a coroutine

thick terrace
#

you could maybe load an empty scene non-async, then load your main scene additively?

quaint rock
#

coroutines need a object to run on

#

your main scene load is not addative so the previous scene is getting unloaded stopping the coroutine from continuing

thick terrace
quaint rock
#

but yes addative loading needs there to be one active scene already

#

generally i have a init scene that is the first to load, and never gets unloaded. it contains core stuff required by the whole game

hybrid orchid
#

So I have a question. I wanted to make a 2D management game where you build up your clan essentially you can have up to 30 clan members at once with reproduction, dying, and etc. So my question, would all of these be 30 separate game objects with all of their stats defined, saved, loaded, etc. and then just reused when one dies and another is born or is there a better way to do this?

vestal crest
#

chatgpt says its not possible to load scenes at the same frame. at least it says very complicated