#archived-code-general
1 messages Ā· Page 179 of 1
the states changes which one is playing
cool but you didn't show that code so it's hard to tell what's going on
the running one dosent play at all anymore but the rest work just fine and flip correctly
all that changes there is what i showed what else do you need to see??
the code that actually manipulates the animator. The whole script would be idea
create 2 animations, 1 for running right and 1 for running left
https://hatebin.com/zbazggunbr this what u mean?
you're only ever setting the running state if you flipped this frame
otherwise you're doing this:
else
{
state = MovementState.idle;```
so it makes sense that you're not seeing the running animation
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)
Unity says "cant convert type float to AnimationCurve"
xCurve.curveMin = windDirection.x;
does the MinMaxCurve store 2 animationcurves?
sorry use constantMin
im not every good at coding so sorry to ask but could you give an example on how i would be to fix that then?
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
Just think for a minute about when you should be setting the state to running and when it should be idle.
Then write the code
you can do it š
note that horizontal returns a value between -1,1 which represents A and D on your keyboard , and D is 1
thanks for the help im still pretty lost but ill continue trying at it
have you done the first part? Thinking about what circumstances should do each animation?
yeah
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
but look at your code
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?
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
the "saved in another class thing" sounds vague but also not that relevant
- get a reference to it
- serialize it with a json serializer
- 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
does anyone know how to fix this so the summary will display?
Pretty sure SOs are serializable by JsonUtility.š¤
So's work fine with JsonUtility
It kinda sounds like you're saving several objects in one file/string.
those look like references to SO's not the so its self
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
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
but I'm sure it's a very simple mistake
can just use order by
keep in mind you can not store the sorted result as a Dictionary
but they are actually sorted
just missing about 30% of the elements
output2_ is the original Dictionary
You are serializing the Save object. It only has references to the SOs.
@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
Not just FromJson. ToJson too.
just a regular class
I know but I want to create my own method, I just want to know why entitiesOrdered has about 30% less elements than it should have
where did I go wrong?
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?
yes
dict.OrderByDescending(x => x.Value).ToList();
I want to avoid Linq
I just want to know why it's not adding every element from the original Dictionary lol
would take that over trying to do your own sorting
I probably messed up counting the i or the index
but that's just it
I just can't find the error
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
Ah yeah, you need to use the Overwrite version for SOs
just use a regular class with [Serializable] on it
You wouldn't have this specific issue if Player was a plain class
ok better question, why are you using a SO for simple data like this
what benefit is that giving you?
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.
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
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.
generally its good to keep your save data seperate from other runtime data
You need to separate immutable data from non immutable.
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
non immutable
(Aka mutable)
Right.
š
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
many good places to use them
but those uses are more like assets
since they can reference anything from the project
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?
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
Do tell. Iām very familiar with BTs but I havenāt found a good use case for implementing them as an SO
but like any tool they will just cause friction if applied from the wrong use
the trees themselfs are are a type of SO, then inside the graph each node and blackboard variable is a SO stored as a subasset
doing this instead of SerializeReference for nodes and blackboard vars since its less fragile
I'd definitely use SOs for item, skill or effect definitions.
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
Word.
but yeah between them in graphview was pretty easy to roll my own behaviour editor
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?
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
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
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
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).
anyone?
PlayerPrefs isn't really meant for saving game state data, it's more about saving preferences for the game player (aka the actual application). you can use it to store save data, much like you can use a hammer to get a screw into a wall but that doesn't mean that it was intended to be used for that.
Also if your build is for windows you're bloating the registry with your save data
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 š¤·āāļø
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
it wont but i would still put it at 0,0,0
so if it ever gets offset its easy to put back, and you can see what that offset would be
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
You only need to calculate the offset once per object, not for each vertex.
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
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
unless its a truely massive mesh you can do it per frame fine
1k is nothing
i see
dont worry about it till its a problem you can measure
true
but also if it was removing 1 subtraction would not help that much
is gpu readbacks every frame a bad idea for this ?
i dunno the perf cost of that
vs getting it cpu side
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
i had thought about compute shader but im told sending data back to cpu from gpu isnt particularly fast
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
if the vert shader does it then its doing it every redraw
so would rather avoid that
would just see if it works before getting too in your head about it
after some experimentation apparently summaries really dont like the & symbol
not sure what the issue would be, vertex shader depending on the task would be ultra fast, its literally meant for moving verts about
because its a one time job vert shader runs every time
and you said it could update everytime the mouse moves, so that is essentially per frame anyways
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
If you don't need that data on the CPU side(for colliders for example), a vertex shader is definitely the best solution.
The issue is not with generating buffers but reading/writing into them.
oh
thing is if its truely a visual only thing vertex shader is just best
You move data between devices(RAM - VRAM). That's the expensive part.
does not matter if its every frame, its used to dealing with millions of verts per frame
why vertex shader and not compute though
id use vertex to morph pre-existing mesh
didnt think it would be for generating new mesh
mesh along splines to the mouse position
so assumed you are modifying something you are rendering
Compute would just add overhead for the same result (if you don't need to move data back to CPU). It is also way more complicated API wise, since you'd need to get the mesh buffer and modify that in the compute shader.
problem with compute is its like 2 round trips for this usecase
That might require a new mesh indeed. I don't think you can change the size of an existing vertex buffer.
yeh thats why i'd need to create buffer of the size i need each time
yeah i was assuming you are modifying existing verts
if the vert count changes you need to do it on the mesh level
yeh it would change depending how far the mouse is
really just try it
Well, in this case you test both CPU side and GPU side to see if GPU overhead is worth it.
okay
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
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;
}
that will work but will be costly, much more then any of the sorting algorithms C# already has out of the box
more than Linq?
since for each item you add you are looping the whole collection again
also you should confirm Dictionary actaully maintains insertion order
if you need to constantly set the order, i'd look into another collection . . .
its based on a hashmap so unless they got something else in there to help it wont maintain order
dictionary doesn't seem like the you want/need . . .
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
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;
}
.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
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
sure depends on how you are writing this to file
do you think my method will perform better than Linq's OrderByDescending ?
it will not
like this
cant use [System.Serializable] again so currently the second one is usable but not serializable
it will not since your method is really just getting max many times in a loop, and does more mutation
there is no reason you can not, you can apply the attribute to any type
Who said you canāt
okay so apparently it randomly decided I can use it more than once, not sure what was wrong before than
i think you put it above the comment
then it worked when it was the line above the class
probably just placed [Serializable] in the wrong spot . . .
wouldnt be the first time I've messed up positioning
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
I dont wanna ping the guy n disturb him but thx for the help i finally got it working
Discord is giving me a null error and claiming this is an object
is Unity just being broken and needs a restart?
what?
what error message are you getting
ok on line 35 of Sim_Entity.cs you are trying to use a null variable
then either Forces is null or Forces[i] is null
its not null, and its not an object
- Yes it is, or your wouldn't get an error
- Everything in C# is an object
this is the relevant code that comes before and after that
right so you never actually initialized any of the elements of the Forces array
so they are all null
hence Forces[i].force is the same as null.force
hence the error
so I need to set the values of each individual element without actually calling those elements?
- You need to assign each element of the array to an actual object if you wish to use said objects
- not sure what "calling those elements" means
elements of the array, elements 0-2
also what's with this for loop and switch? This is so weird
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
its because I'd like the values to be able to change situationally
Forces[0] = new(put your force here, put your target here)
Same with force[1] and [2]
these are just hardcoded though
not situational at all
if you want it to change based on a situation, that situation should change these values
I'd later change the code to ask for other things and calculate the value, right now they are hardcoded
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
if I put it in Start than they only get set once and never again
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
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
If you want to be able to add more you should be using a List rather than an array
Lists can be resized, arrays cannot
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
because it forces you to recreate it, that also entails setting the values again
you really might want to experiment with this outside unity, so you can run it quickly/see the outcome
You are not forced to recreate a List to add things to it.
would I still have to create each member of a list or does creating a list create them?
you still have to create each member
yep, Linq takes 16687 ticks to complete, my method takes 35073 ticks to complete
count2 uses Linq's OrderByDescending(x => x.Value)
count uses my method
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?
this wil not work
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
wait... this didn't actually sort my dict OrderByDescending(x => x.Value)
that's why it took half as long
lol
Linq doesn't sort things in place
it returns a new collection
ah
also I don't really understand what you mean by sorting a dict anyway - Dictionaries are not ordered
this seemed like it should work, if it doesnt exist it should be null, which should trigger the addition of a new item to the list
unlike an array, the list just starts empty. It doesn't start out with null entries
the list starts empty, not with null entries
doing Forces[i] will be out of range if there is not that many elements in the list yet
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
}
};```
list still starts from 0 when counting items, right?
of course
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);
}
why not just:
Dictionary<string, uint> dict2 = dict.OrderByDescending(x => x.Value).ToDictionary();```?
But again
this doesn't do anything
because Dictionaries are NOT ordered
YOu can't rely on it
it's undocumented behavior
and subject to change or be different on other platforms
For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<TKey,TValue> structure representing a value and its key. The order in which the items are returned is undefined.
https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=net-7.0#remarks
If you need an ordered dictionary is it worth just having a tuple list?
if they need to look up values by the key efficiently, a list will not be as fast
At that point, just wrap your data in a separate class/struct.
but if they really just want an ordered list of pairs, then sure
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
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
I see, I will probably still let the player to scroll and select orders
The full Image component š
so I will just have to disable levels select action
?
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
I see, so to make everything less visible?
Yeah showing that āthese are not clickableā
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
Sure, that feels like more of dockable window style (which you can also click background)
But anyways, just preference
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)
// ...
}
Yeah, that's one way. Another is just not to invoke the action.
what do you mean?
yes.
you mean?
private void OnEnable()
{
onOptionSelect += SelectOption;
}
private void OnDisable()
{
onOptionSelect -= SelectOption;
}
No. Where do you invoke the onOptionSelect?
this isnt invoking the event, thats adding/removing listeners
public void InvokeOptionSelect(OptionSelectButton option, bool value) =>
onOptionSelect?.Invoke(option, value);
Ah, I remember now.
That's the code that I said was over engineering.š
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);
The issue is that you're abusing anonymous methods/lambdas. So you don't have full control over them.
why is this a UnityAction š¤ is there a benefit to actually using them
why not? they have done a UnityAction anyway
so how do I disable this event?
Just don't call the InvokeOptionSelect method.
oh, I see now
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
public void InvokeOptionSelect(OptionSelectButton option, bool value)
{
if (bool)
onOptionSelect?.Invoke(option, value);
}
š¤ why does that 2nd parameter even exist lol, just dont call InvokeOptionSelect
because sometimes I have to select a button regardless if it's already selected or not
sometimes the value is option != currOption
i must be missing some important context, but this definitely does seem overly complicated
or overengineered
just don't wanna call the event directly in another classes
you can't anyway. events can only be invoked by the object that owns it
how can I inherit from UnityAction?
in order to make a bool like CustomUnityAction.enabled
š¤ what
no..?
yes.
yes, that's literally the entire point of the event keyword for a delegate
You have a function to invoke the event for you, but the event can only be invoked from the object that owns it
yeah it's great for keeping scope to a minimum
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?
just save the variables separately
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
You're trying to give objects responsibility/functionality that doesn't belong in them. Delegates/events are not supposed to be disabled or enabled. A ui element can be enabled/disabled. The UI element should decide whether it should invoke events belonging to it or not based on its state, not the state of the event(which shouldn't really have any state aside from subscribers).
id honestly just store it in the class. i mean this will store it anyways, u just dont see it now and cant use it for visualization or anything else
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
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
so no way? š
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
Probably not. I don't think it's possible to inherit from delegates.
I see, thank you š
@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
so, to make a full class
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
and that's all?
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;
}
I see, I will try that, thank you š
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#
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?
each platform prefab could have a spawn point and just create a random chance of spawning an enemy on that spawn point
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.
Where do you have this data from in the first place?
I create it.
Unless you want to know off of what I create it
Can't you assign the neighboring polygons when creating each new polygon?
No, I don't think so, unless I ran the code above every time I created a new one which would have the same effect
I take it from mesh data
kind of
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.
That would take long no?
Considering there are around 100 (convex) polygons, each with 3-6 vertices each.
Which is indeed the case
Then there's not much you can do imho. Just do it asynchronously over several frames if you can afford it.
Actually, I think there might be a better solution now that I think about it, but I am still not sure what it is. I'm going to draw a picture quickly so that it would be easier to visualize
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
Okay so, imagine this, where the blue outline is a window frame and the red pieces are glass shards which are stored using the same List<Vector2[]> where every Vector2[] is one of the red polygons that you can see (each separated by more vibrant red lines). I need to get every connected group of these shards.
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
This isn't a programming issue. Use the Frame Debugger and step over the rendering
Sorry to ask but how can I use it
Is that for glass breaking effect or something?
never heard of
Indeed
Do you have to do it at runtime?
Yes
Why?
It's like realistic glass breaking. This glass isn't pre-broken, the player can break it
sorry to ask but how?
Google it
I get it. I don't get why it needs to be done at runtime(finding the touching shards).
just google it š¤Æ
No can do. As I mentioned before, this is a "realistic glass breaking effect" which is simulated at runtime. It must be done at runtime because of the variation of the glass shapes there are, and also the player has a gun which he can shoot at any point of the glass, plus there is reqursive shooting, so there really isn't a way to pre-simulate this
So you don't know the shard vertices before the glass is broken?
I have a fracture pattern (picture) what is used for the glass breaking of what I do have the vertex data which I store in the script, but that's really all
That's really all you need.
Just cache the shards as a list of C# object having a reference to their neighbors.
Well, I suppose I could do that, but that would require me to change the script a bunch, but that's for me to figure out, thanks for the help!
Vertx, i found a problem at DrawTransparentObjects. How can i see what made this problem?
Post a better screenshot of the issue in a relevant channel, #š»āunity-talk is also fine
added vertx
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
Maybe have the scenes inactive till the second is finished?
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
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
You just have 2 scenes, so no need for a list
Use 2 variables and check them both in the while loop
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
yeah would not work for your purpose then, asmdefs are only about C# assemblies not anything precompiled
are inspector rotation values euler angles or local euler angles?
as far as data goes only the local values exist, the world ones are computed on request when accessed
For rotation, it's special local euler angles that can have negative angles. It doesn't always match transform.localEulerAngles.
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:
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
Try looking at sub scenes?
isn't that an ECS-specific concept
No I haven't. what are those?
They seem pretty easy to use, auto does the ECS stuff for you
right, it converts a gameobject-based scene into entities
using the bakers you've defined
and loads instantly - so the video I watched said
i'm not sure this is relevant...
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.
You still have scenes, you create a sub scene.. and load that
Seriously, it is relevant.
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
Gonna use it for my fps vehicle game driving around a city.
that is an interesting thoght! Thank you š
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.
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.
call a method, like Init on a script from the prefab when you instantiate it . . .
you can pass an argument like a struct or any variable(s) the instantiated object needs . . .
Thanks. I have a bunch of those. But that doesn't prevent from Instantiating and not calling Init(). I wonder if there is a cleaner solution that would imitate a construtor.
i don't see how you forget. it should only be in one spot, no?
One spot for each script you add... A prefab can have multiple scripts on it...
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 . . .
Isn't calling Init( ... params ...) already calling a custom method on them?
yes, i'm saying you shouldn't have to call that on multiple scripts . . .
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
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 . . .
how would I assign the current scene objects to a prefab? I believe it cannot be done, only other way round
see dependency injection. this link is pinned in #š»ācode-beginner
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) . . .
this is the same thing as calling Init()....
but called Initalise()
I didn't scroll up your convo. I'm just answering that one question
the name of the function doesn't matter
Ok, thanks
it's basically what Random described after anyway
There's only so much you can do here. Constructors are guaranteed to run because they're part of the object's lifecycle -- you have to run a constructor, by definition.
Ok, I am using that already, I thought there might be a better option
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.
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 . . .
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..
Yeah that's how I would do it
this would avoid re-computing it if nobody cares about it, too
of course, I think I need to re-consider my "multiple sphere-casts for every part of the target's body" scheme, first...
Custom setter that does nothing if the frame is less or equals to the previously recorded one, or that the value hasn't changed
(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
maybe use a struct with a prev value and cur value property? set the cur value to prev value when the frame changes and update cur value to the new value for 'this' frame . . .
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.
do you need multipler casts for each body part? are you able to combine some of the body parts to use one cast? also, have you tried pinging or calling the cast every X frames or every X seconds?
yeah, all of these are valid options
spreading it out over several frames, notably (I want a smeared-out value anyway)
if the field does not need to be serialized, I'd just remove the [SerializeField] and then use assertions to make sure they're set properly
Sounds like a good idea actually
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
any reference field, like a component, can be dragged. i find that an easy solution. errors from gameplay will tell you if it's not assigned (you can also look in the inspector). another option is to check/set them in Reset or Awake as a back up . . .
Asserts should be used for "shouldn't-happen" situations
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
Here's a code sample which might clarify the question https://pastecode.io/s/kukrri5u
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 . . .
Wow... So does it mean one would have to reconfigure the whole project to work with ECS?
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
presumably so, yes.
download NaughtyAttributes
https://dbrizov.github.io/na-docs/attributes/meta_attributes/read_only.html
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
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
Thanks
I tried this for additive loading but it didn't seem to work for me. I'm not really sure how to apply it
That while condition looks backwards
Also unclear where the activation is being allowed to continue
It is backwards and yes, you prevent the scene switch from happening by setting allowSceneActivation to false
How do I delete the gameobject I created when I stop playing?
Set scene activation to true AFTER the while loop
Destroy(obj, myAudioClip.length);
optimal to create a new gameobejct everytime I wanna play audio?
its for UI audio, 10 second clips max
just have a persistent audio source that you call PlayOneShot on
I wanna be fancy and do it through script š
You can use PlayOneShot on an AudioSource or even just https://docs.unity3d.com/ScriptReference/AudioSource.PlayClipAtPoint.html
i wouldn't call this "fancy"
PlayClipAtPoint doesn't require an actual audio source in the scene
I need to set the mixer, so cant use playatclip...
aha!
This function creates an audio source but automatically disposes of it once the clip has finished playing.
I remember seeing this behavior in NeosVR, but I didn't observe it when using PlayOneShot. So that's what was doing it.
then probably PlayOneShot is your best bet
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
how do u set the mixer do?
PlayOneShot is called on a specific audio source
PlayClipAtPoint is not
all of the settings of the audio source are respected when using PlayOneShot
So, u need a persistent source either way huh
no, your scheme would involve creating and destroying them repeatedly
as would using AudioSource.PlayClipAtPoint
I was going to create only 1, but I dont know how to destroy it when applicaiton stops playing
roger
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
it's because you're creating an object in OnDestroy
do it in the code that calls Destroy instead.
I meant when application STOP playing...mb
you were right
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?
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
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?
Well a sprite is basically exactly that - UV pixel coordinates into the original texture
I see, I see,
you can modify the sprite rect with https://docs.unity3d.com/ScriptReference/Sprite-rect.html
is there a way to do "OnCollisionEnter2D" but for a specific collider and not the gameobject that the script is attached to
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
where exactly would i find this
like
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
StartCoroutine is not required for LoadSceneAsync but it's definitely convenient
If you want to start a coroutine you need a MonoBehaviour to run it
How can I call it without coroutine? I was trying to use ScriptableObjects as Managers for my project, but the SceneManager is giving me some trouble due to this reason
I mean you can just subscribe to https://docs.unity3d.com/ScriptReference/AsyncOperation-completed.html
Or as long as you pass the AsyncOp somewhere you can manually check the progress and isDone etc https://docs.unity3d.com/ScriptReference/AsyncOperation.html
Ok I see, thanks a lot!
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
Then you did not implement it correctly.
(Or I did not understand what you were trying to do)
I updated today lol
ive figured it out now, i just didnt calculate quaternion rotations properly thats all
but it wasnt to do with the character controller just lack of understanding
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
The picture you're making is 256 by 256
set it to 1920 and 1080
At these locations
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
yeah lol
omg it looks so fancy what
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?)
no errors related to the camera no
changing the output size didnt change anything either
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
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);
ur destroying other probably the collider, not the gameobject
How would I fix that?
other.gameObject
thanks š«”
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?
Does the new visual studio have AI built in??
yes
Its called Intellicode
Yes, it's called IntelliCode, although it's been in VS since 2021
microsoft made it
Microsoft also own github, not surprised if they shared code from github pilot
I mean that's still pretty amazing I've been typing it out since 2017
while tabbing the hell out of intellisense ofc
yea half my code I just tab and it knows what I wanted
it is pretty creepy sometimes
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
is level editor a regular class ? otherwise this would not make sense
wdym regular
regular POCO. not monobehavior
maybe thats why it didn't suggest it if it's MB
MB don't get new()
then yeah you don't use new()`
exactly
oh you're saying intellicode put that?
yeah it doesn't know about GetComponent ig, bummer
It did 
But then i realised i got the wrong class and now the intellicode is different
even though they're both monobehaviours
turns out the issue was with the target mesh, not the code lol
thanks š
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
Github Examples you mean ?
or you mean VC built in VS
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.
do yall name base concrete/abstract classes with a suffix of Base
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
That makes sense I think
maybe if it was going to be ModuleBase with VisionModule and HearingModule
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?
you want isActiveAndEnabled
tried, doesn't work
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.
i am unclear what it means for none of the scripts to work
They just don't do anything
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
that doesn't work too
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
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
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.
yes, the gameObect that has a script can be inactive or active
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);
}
The rotation on it should be fine I use configurable joints a lot, though the settings are tricky. If you set the rotation to quaternion.identity, the configurable joint is constantly gonna fight those rotations you apply in fixed update
I still do not understand. What is the actual problem?
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
yes, the gameObject is activated when the button is pressed
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
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?
do you have "Low Resolution Aspect Ratios" enabled on the game view?
If so, any of the Aspect options will be at half-res
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?
its on free aspect
the checkbox is only active (and relevant) on higher DPI screens
When is there even an advantage to using Update over FixedUpdate?
when you want to run something every frame, not just 50 times per second
moving the camera in FixedUpdate would be awful
the box is not checked
yes, i know the functional difference between them. but not why/when you'd want to use one over another
What if you pick a specific resolution?
fixedupdate always seems more precise
sure, but it also might not run for several frames
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
yeah that works but i want it to work for free aspect
exactly, that's the issue
ohhhhh. thank you, that was helpful :)
so basically I don't want listeners to be added twice
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.
do you know why it would be off for a free aspect ratio?
so do you see gameObject.activeInHierarachy: true; [name of object] twice in the logs?
or once false and once true
once false and once true
now I have realised why it's so
it works when GameObject is disabled in the inspector at the start
I wouldn't expect it. Maybe it still pretends the DPI is lower?
if you deactivate the object after you instantiate it, it's too late
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
yes.
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 š
really? They're usually just... working?
I'm gonna have to make a new project and check the behaviour...
i mean yea they exist in unity because they work. id have to see more settings or what you're really doing to understand whats not working though
my player is made up of 14 of those configurable joints
so I have this problem where after some time of re-using pooled projectiles, some projectiles kind of get messed up positions and rotations
I'd guess it's because some of the projectiles dont get resetted properly
any ideas why?
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
PlayerController: https://hastebin.com/share/ajuhuxaxet.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
EnemyTouch: https://hastebin.com/share/epedohixeb.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
- You should not use static variables to communicate between scripts like this. It will lead to all kinds of issues.
- The way you are using StopCoroutine is not correct and will not do anything
- It's unclear which object EnemyTouch is attached to, but if that object is getting destroyed the coroutine will cease running when the object is destroyed
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
or the IEnumerator value returned by invoking the coroutine itself (the same instance that's passed into StartCoroutine originally)
surely there could be multiple enemies
enemy touch is attached to zombie prefab
yeah so
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
So I should just put regen health and lose health in player controller script?
yes
Mate ngl I dont know what I do most of the time
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)
precisely.
the zombie should not care about the intricacies of the player's health regen
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.
I originally bodged this by just making a singleton "input manager" class that has the Player Input component on it
it would reference the player and forward all of the events to them
- If you're using PlayerInput component the convention is that there should be one PlayerInput per physical human player
- You can make a script that handles the input and exposes it in whatever way you wish for other scripts to use.
- You may also want to explore other input handling strategies such as the use of the auto generated C# wrapper class or InputActionReferences
alternatively, just stick it on the actual player, and then have the player tell the weapons about the input events
InputActionReferences are lovely
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)
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
yep yep
If you want a "globally accessible state" kind of pattern, yes that's basically a singleton
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!
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?
Yep. You might have separate input actions for vehicles, but the vehicles still doesn't directly talk to the input system
https://hastebin.com/share/homavosuce.csharp I did it, but the issue is still happening, it is weird to me that the effects will stop but the health wont regen
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Thank you very much for the help.
Thanks
OnCollisionExit is not going to run if the enemy is destroyed
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
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!)
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
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"
Visual Coding With PlayMaker Cuz why not
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" "
ok step back , what is the direction that you need?
a direction vector?
what do you want to get in the end
In my head, i want to get the look rotation from real handle position to handle position. So i can create an Direction enum and set it to "Top" for instance by checking "If less or equal to this". After that i can integrate that to my player controller to do special things.
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?
show code
i have a suspicion you didnt swap z and y
Here i did one 
the code where you extract both vectors
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?
movement and ui
You're defeating the poing of scenes, you should just make your own pool system for your objects, no reason to rely on unities system if you're doing your own custom stytems basically.
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?
this is a good start https://github.com/starikcetin/Eflatun.SceneReference
I'm not using scenes.
what does that mean i dont understand
then use scriptables or any referenceable container to represent your levels
You're trying to load scenes, why not just load and keep your data in memory and use it when you need to?
the "hardcoding" part simply comes from lack of references
can you elaborate what are you advocating here?
i believe this was an attempt to get around the hitch that occurs when loading a new scene
this was asked about yesterday
hmm, not a bad idea, I'm against SO's.
Currently I'm referencing by ID and using a json "Data table" for other data.
Depending on what data @vestal crest is using, there's very little need for "scenes" these days. To me "I want to load all scenes" screams that he shouldn't be using scenes anyways.
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.
little need for scenes huh
So load all scenes huh
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
The lads loading all scenes at once... Where did I say "Don't ever use scenes"
well, "there's very little need for 'scenes' these days" sounds relevant here.
He's trying to do the literal opposite of what scenes offer.
you are thinking in terms of data loaded, you ignore the fact what scene offers as means of project organization and content creation pipelines
Just pool and use what you need, it's not complicated.
The guy is literally loading all scenes.. What are you trying to argue?
it is very common for large games to utilize massive amounts of scenes that are segmenting a single open world, for example
I want to organize scenes and then use all of them at once
yes
Which is normal for complex projects
thats how it works, a lot of times
actually im not loading all scenes. i want to load specific scenes at the start of the games. like UI scene MainScene
Sure mate, you are 100% correct, answer his question.
hm
oh, this was someone else entirely #archived-code-general message
UI's shoulnt be seperate scenes.
Complex project
why wouldnt be?
Why would it?
I dont have a problem with being seperated.
But why?
You're just adding complexity and then trying to merge scenes UI and Gameplay.
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
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
but that was more for workflow reasons with mulitple team members
Sure, but UI shoulnd't exist as it's own scene, a prefab is organized just as well and less combersom. But do whatever you want.
if you want do UI with scenes, just learn about addative scene loading
and find a way to make the references required after
i still dont understand your initial issue, you can just remove input check and rely on progress, you can LoadScene without async, im not sure what is the issue
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.
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
if mainsceneoperations progress is completed is it sure to other all async op is completed?
i think both ways are okay. you dont need to put your ui prefab to other scenes you can just load the scene.
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.
i dont think there is a correlation between main and additive scene loading ops, youd have to await all of them
can you check if all of your ops are >= 90% every frame, then allow activation on all of them?
On top of loading in a scene you also have to grab all your references in that scene and set up all your events.
im not being stubborn as i said bot ways are okay to me. i dont have problem with your solution
i tried it but it doesnt work
it never works that if block
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
what happens if you do that?
what do you mean doesn't work?
it doesnt return true
probably because its never called
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
isdone cant be true because allsceneactivation is false
mainsceneprogress is 0.9f. mainsceneprogress if works but additivescenesprogress if doesnt work
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
because i want to activate the scene if all scenes are loaded
actually it loads 3 frames later
whats the progress value in the debugger?
often the scene activation is the longest part unless its a very asset heavy scene
0
since the scene activation is where its running all of the Awake, Start and OnEnables in that scene
any errors? scene added to build index?
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?
what is loadingscreen
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
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
it should load in background
while the coroutine is running, the issue may be that single mode and additive mode must be piped
what ever started this coroutine you need to ensure it does not get unloaded with the main scene load
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?
it unloads when main scene is activated
yes probably
no but this function loads what you call the main scene, but htis function is a coroutine
you could maybe load an empty scene non-async, then load your main scene additively?
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
this still happens with don't destroy on load objects
am talking one of the issues with the previous code
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
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?
chatgpt says its not possible to load scenes at the same frame. at least it says very complicated