#archived-code-general
1 messages · Page 259 of 1
Destroy destroys whatever you pass into it
if you want to destroy the GameObject, pass the GameObject in
How do I pass an instance of the class that the script is attached to
this is the instance of the class that the code is currently running on

Then how do i destroy the object and not just the script
but from the script that the object is attached to
If you want to get a reference to the GameObject the script is attached to, that would just be this.gameObject or just gameObject (you don't need the this)
nice ty
ok ive been racking my brain at this for a while im trying to traverse a graph essentially which is my list<list<int>> and im trying to make it start in a random place and assign that to 0 and then adjacent tiles which are the ones to the left and right and above and below it it will randomly choose to go to one of them and assign it 1 then do this so on until roomCount is reached
{
new List<int> {-1, -1, -1},
new List<int> {-1, -1, -1},
new List<int> {-1, -1, -1}
};
public List<List<bool>> roomsVisited = new List<List<bool>>
{
new List<bool> {false, false, false},
new List<bool> {false, false, false},
new List<bool> {false, false, false}
};
public List<List<bool>> roomsValid = new List<List<bool>>
{
new List<bool> {false, false, false},
new List<bool> {false, false, false},
new List<bool> {false, false, false}
};
// Start is called before the first frame update```
{
roomCount = Random.Range(3, 7);
for(int i = 0; i < roomCount; i++)
{
horizontalChoice = Random.Range(0, 3);
verticalChoice = Random.Range(0, 3);
if (i > 0)
{
while(roomsValid[verticalChoice][horizontalChoice])
{
while (roomsVisited[verticalChoice][horizontalChoice] == true)
{
while (horizontalChoice != leftCheck && horizontalChoice != rightCheck)
{
horizontalChoice = Random.Range(0, 3);
}
while (verticalChoice != upCheck && verticalChoice != downCheck)
{
verticalChoice = Random.Range(0, 3);
}
}
}
}
upCheck = verticalChoice - 1;
downCheck = verticalChoice + 1;
leftCheck = horizontalChoice - 1;
rightCheck = horizontalChoice + 1;
for(int a = 0; a < 3; a++)
{
for (int b = 0; b < 3; b++)
{
roomsValid[a][b] = false;
}
}
if (upCheck > -1)
{
roomsValid[upCheck][horizontalChoice] = true;
}
else if (downCheck < 3)
{
roomsValid[downCheck][horizontalChoice] = true;
}
else if (leftCheck > -1)
{
roomsVisited[verticalChoice][leftCheck] = true;
}
else if (rightCheck < 3)
{
roomsVisited[verticalChoice][rightCheck] = true;
}
roomMatrix[verticalChoice][horizontalChoice] = i;
}```
is this a graph on a grid?
i guess yeah
is it a directed graph
yeah it should go from start to finish
uh, but are the edges directed
like two positions might have one-way travel between them
all the positions will be one way travel
if you are trying to search, you should use a graph.
if you are trying to create a graph on a grid that satisfies specific constraints, you want the wavefunction collapse algorithm
and this does not sound like a directed graph
you are building outward, but that does not make the graph a directed graph
also, don’t do all this in a Start() call
make an actual class to handle this. a POCO
The number of loops make this look insane
Hi, I have a line of code where I want to aim a hose and spray a target, is this right?
hose.transform.eulerAngles = new Vector3(0, 0, Vector2.Angle(hose.transform.position, target.transform.position));
no calculating angle between 2 positional vectors makes no sense
i want the hose to point at the target
i would do something like
var direction = target.transform.position - hose.transform.position;
hose.transform.rotation = Quaternion.LookRotation(direction.normalized, Vector3.up);
it's 2d, is vector3.up the right thing? I want to rotate the z
ah i was assuming this is 3d
for 2d i would be tempted to just manually do the math
var AngleRad = Mathf.Atan2(target.transform.position.y - hose.transform.position.y, target.transform.position.x - hose.transform.position.x);
var AngleDeg = Mathf.Rad2Deg * AngleRad;
hose.transform.rotation = Quaternion.Euler(0, 0, AngleDeg);
hi im using this line of code:
lastProp.GetComponent<Rigidbody>().AddForce((propPos.transform.position - lastProp.transform.position) * 45, ForceMode.Acceleration);
to move my prop to its destination it works but in like 1 in 5 times it just starts floating around its destination how do i fix that?
would normalize after your vector subtraction
the multiply it by 45 will not be consistient since the length of the vector will often be much larger then 1 unless you normalize it first
you mean something like this?:
Vector3 dest = propPos.transform.position - lastProp.transform.position;
lastProp.GetComponent<Rigidbody>().AddForce(dest.normalized * 45, ForceMode.Acceleration);
yes though dest is a bad name for it, since its not a position in space its a directional vector
yeah my bad but it didnt fix the problem :((
assuming it greatly overshoots, because the velocity does not get smaller as it approaches the target
it could be scaled down based on distance to target
maybe the problem is my if statement
private void FixedUpdate()
{
if(itemHeld)
{
if (lastProp.transform.position != propPos.transform.position)
{
Vector3 dir = propPos.transform.position - lastProp.transform.position;
lastProp.GetComponent<Rigidbody>().AddForce(dir.normalized * 45, ForceMode.Acceleration);
}
else
{
lastProp.GetComponent<Rigidbody>().velocity = Vector3.zero;
}
}
}
that makes sense ill try that
should my State be ScriptableObjects or just classes?
depends on context
wait it depends on the context?
basically my State class is an abstract state for controlling Player's State, AI's/Enemy States, and some Objects' State
doesnt make much sense to use SO here, SO is meant for immutable data and just being a data container.
and you would have to create a new instance for each object anyways
okay I found an article on that, so im just asking whether I should change my approach
it would only make sense here if they wanted to serialize data for it. but would come with the over head of needing to reference and instantiate
i have my states as monobehaviour for the ease of setting up unique enemies in the inspector.
theres a ton of ways to implement it, a State can be anything. as long as its easy for you to use then use it
does referencing StateMachine in States cause problems in the future or is it having some unnecessary computational burden on the game?
would say depends on implementation you got, you are getting maybes since state machines are just a lose programming pattern that can be used for many many things and implemented in many ways
i dont think it makes sense for the states to know about the state machine, but ive seen implementations online where people do it like that. Its not like it'll matter in the grand scheme, there will be 0 performance difference
its just a matter of storing a reference
Im even referencing player's controller in one of the State's derivatives. Maybe I should just let the states have their neccessary variables instead of passing in all of them
relaly not sure what the point of this state is, but yea this state has way too much control over what happens. The whole stateMachine.SetNextState(new SlimeIdle()); part needs to go. This is gonna stop you from making reusable states
Im citing player's position in the State and constantly updating it every frame. So if I have 1 million entities in the world would that be ridiculous?
if you have 1 million entities in your game, your game wont even run
this code is definitely a mess, why is OnEnter calling BaseUpdate
any idea how you would implement this otherwise? Im guessing you are storing Conditions for transitions in your State and have your FSM check whether it is suitable to change State. Then, you make call directlyfrom FSM and avoid unnecessary StateMachine inside State?
my enemies are simple enough that i dont even care about transitions. If they can enter a state, they enter the one with the highest priority
there is, but thats not what i was referring to. I assign each state a number and then just check which one has the highest number
let's say I want to make a horde of enemy acts differently. Having priority queue so an enemy would go and be the defense line. Others notice some of their teamates are defenders, they change their priority to ranged attack
would be cool
a priority queue wouldnt really affect what happens here, the enemies in this case would need a sense of their team. You could pass this as a parameter to each state, then they lookup what role is lacking
Actually this wouldnt really happen inside the state machine, being ranged/melee/whatever would be the states. An enemy controller script would be looking that information up, and then requesting a state transition
Hi, I believe I have some type of memory leak
I regularly reload a scene using SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); . However, after each reload. it seems that the game starts using 0.01GB - 0.02GB more RAM.
I am using memory profiler (https://docs.unity3d.com/Packages/com.unity.memoryprofiler@0.2/manual/memory-profiler-window.html#capture-a-memory-snapshot) but there are too many variables to navigate through sanely.
What are my options for fixing this?
wdym by making reusable states
oh ye
i forgot to move that to the SlimeMovementBase
but it is going to be depracated soon with better management
Does this increment indefinitely? Was this tested from the Unity Editor or a standalone build of the application? The image shown had a decrease of about 200 bytes from 31.4KB to 31.2KB.
does anyone know how RainWorld AI works
There are talks on youtube that cover the concept of it, which is probably the best you're going to get:
https://www.youtube.com/watch?v=6Ji2q3WQE78
Sign up to Milanote for free with no time-limit: https://milanote.com/thatguyglen
This Rain World documentary details the development of indie 2D pixel art survival platformer Rain World and goes behind the scenes of its creation. Discover more about developer Videocult and its two founders, Joar Jakobsson and James Primate. The very first prot...
there's also the devlog https://forums.tigsource.com/index.php?topic=25183.0
Project Rain World
thanks
ah try this one instead, it should be more complete in terms of missing images and stuff https://candlesign.github.io/Rain-World-Devlog/Full devlog
Hi, I have some code to point a hose at a target point, but it's not quite doing it right, I have a player moving back and forth, their scale x is 1 or -1, when it's -1, the aim is off a bit and I don't know why
var AngleDeg = Mathf.Rad2Deg * AngleRad * tank.transform.localScale.x;
hose.transform.rotation = Quaternion.Euler(0, 0, AngleDeg);```
how does the view model system differ from the entity component system
One separates visuals logic and business logic. The other separates data and behavior.
They're kind of in different realms entirely.
which would be easier for saving and restoring data / application state ?
Like a save system?
yea
im trying to make a hot-reload system
and i would like it to be easy for people to implement hot-reload compatibility
without for example, needing to make every class they use/make annotated with serializable annotations and such
Then maybe ECS? It should make it easier to save/load the data as is.
Honestly, I'm not sure how view model pattern even is relevant in this context.
the view model pattern basically just ummm operates on read-only data right?
(the actual data is writable outside the model but read-only inside the model)
Hi, I'm writing a server that I'd like to use to perform a number of simulations quickly, independent of frame rate (the server wouldn't be rendering anything). Is it as easy as putting the code in FixedUpdate? I'm having a difficult time googling an answer, and I tried using GPT, but it said to use async/await. I thought async would still run synchronously if there is no await. If anyone could point me in the right direction, I would appreciate it.
Physics.step and multiple Physics Scenes (i think)
If you just want to run a simulation and get the result, you don't need to put it anywhere. Just run the simulation.
I feel dumb, thank you. I had a feeling I was making it more complicated than it needed to be
do note that this depends on what you require
for example, if you need to simulate physics temporarily (eg, for predicions and such) then a second physics scene must be used
if you need to adjust the physics speed (how many times fixed update is called) then Time.fixedDeltaTime and Time.maximumDeltaTime can be used to achive that, the lower its value the faster the simulation will run
thank you, again. Appreciate it
No. Read only doesn't really make sense and is irrelevant in the context of the view model pattern.
how so ?
Because it's irrelevant. The main concept is separation of business logic from presentation.
eg
Label {
public string text => data().text();
// or a more effiecent binding that updates the text variable and causes a redraw when ever data.text changes
...
}
This is just a property that retrieves a value from the data. I don't see how it's alone is relevant to a design pattern.
Typically in Model view you'd have 2 classes that perform the model and the view role. The model class is responsible only for the business logic, while the view is responsible for the presentation logic. The interactions between them and their specific implementation doesn't really matter.
There are all sorts of variations like MVC and MVVM, but the general idea is separation of logic from presentation.
Data binding is not necessarily related to MV.
it decrements in the first restart, then increments indefinitely from there
Does anyone use Firebase there ? I wonder that Is this method is necessary ?
I try to not use this line but other functions related to Firebase working properly.
well based on the docs, if you don't call it firebase might just not work for some users. Why do you want to skip it? Seems like a weird decision
Not a Firebase user but judging from the method name the code is there to ensure that if there are any changes to the backend firebase system your runtime code will be updated accordingly without you having to recompile. So a pretty nifty feature
Thanks all !!
I'm saving data through BinaryFormatter, and I get such error when im trying to save a List of scriptable objects.
SerializationException: Type 'UnityEngine.ScriptableObject' in Assembly 'UnityEngine.CoreModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
i have marked it as serializable
so im not sure what's wrong
- BinaryFormatter should not be used, it's a vulnerability.
- Don't try to serialize a ScriptableObject, create a normal non-UnityEngine.Object class to serialize instead. Only JsonUtility and custom setups can handle ScriptableObject serialization.
or am I trying to serialize something, that just cant be?
I am about to swap it to BinaryReader/BinaryWriter, but for now I need to make it work as it is
Well I don't have List<ScriptableObject>, but instaed I do have
public List<PlayerDeckUnitSlot> unitSlots = new List<PlayerDeckUnitSlot>();
and do they inherit from ScriptableObject
[System.Serializable]
public class PlayerDeckUnitSlot
{
[Header("Settings")]
public UnitData assignedUnit;
public bool isAssigned = false;
}
no
so there is no way to save the scriptable objects at all?
cannot change the architecture for it that far into development
I guess I can make some kind of workaround of it, since i have serializable Dictionary<enum, UnitData>
so i can save the enum, then map it to proper UnitData, then set it to the loaded list
found by Unity Staff member
Can I get same random values using Random.InitState(seed) on different computers? I generate some data on one computer and Id like another computer to generate exactly the same data. I tried to find answers on google so hard, but I feel like some ppl think its possible and some its not
I did try it, but didnt work
https://docs.unity3d.com/ScriptReference/Random.InitState.html
Docs say, same seed will generate the same sequence of random numbers
indeed, if "its not working" something is wrong with how you're generating
It seems it doesnt always work. I generated data twice with the same seed on one PC and data were exactly the same, but when I tried to generate on different PC and compare then data from these two PCs, they werent equal
Kind of a shame you can't have multiple instances of Unity's Random.
so i put my problem in that channel?
Indeed, assigning a particular random sequence to NPC's for example would be very nice but there are ways round this
I would assume it's just using the standard C# Random class.
Right?
I just roll my own Random, it's not that hard
How very programmer of you.
that's me, old, old school
I can see the value of a Static random class, but I think I would have preferred like...
Random.Default.Range(...);
Instead.
Like some default static instance was always available, but nothing was stopping you from instantiating another.
I can tell you that the US Gaming Commission would very much frown on something like that
why is that?
not random enough, way too much chance of it being manipulated
huh
you could use the random for .net instead, it lets you make seeded instances and then you could just wrap and store a instance statically
Ya I'm aware. We talked about that. Was just ruminating on how it's a shame you can't have multiple instances of Unity's Random implementation.
Hey guys, I have an issue where when a level reloads, when the player tries to aim, I get missing reference errors. Ive looked about online but issues tend to be personalised. The thing with my debugging is the references still seem to be there in play mode meaning the script should be able to access it
(for e.g line 125 LeanTween.scale(crosshairDot, new Vector2(1f, 1f), .2f) .setOnComplete(() => Crosshair());, the script still has this game object within the inspector, this is the same for the animator)
Any help?
yeah i have actaully had pacakges break my game because of that, since they were seeding unitys random that other things needed
That's uncool.
did you destroy any object on reload?
yeah sucks since unitys has a few really nice things over the .net one, like InsideUnitySpere/Circle
not that i am aware of, i have a trigger where when the player falls it simply reloads the scene (delay for a fade animation) private IEnumerator OpenLevel(float waitTime, string level) { yield return new WaitForSeconds(waitTime); SceneManager.LoadScene(level); }
Its weird as everything else works and those references are still present in inspector
and the original crosshair() function still plays upon start to make it appear in the first place
meaning... it exists
Yep. Those aren't too hard to recreate by yourself granted, and you can even make extenstion methods for the C# Random to feel like it had those.
But... ya.
Bit awkward.
I kinda having too little info here
maybe get someone experienced in a call would be quick fix
o> will do, its probably something im just not spotting
send UIManager in !code links
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
do you use drag and drop or GetComponent<>
drag and drop
hmm thats kinda buggy
no
also aware the manager can be a lot more optimised
no but i just don't like idea
yeah thats fair
put this before line 125 Debug.Log(crosshairDot, gameObject)
also you should probably fix your other errors so your console isn't spammed with errors
top two errors fire first, then the 125 uimanager error runs same second as the debug log
is it to do with the ui manager instance
dont clip screeeshot of error, show the whole stack trace
also how many logs did you get printed ?
looks like you're trying to use functions on destroyed animator component
the animator it is referring to is still there in inspector which is the confusing part to my head tho
one
also remember to apply to prefab
you could be destroying it at runtime since those are only runtime errors
did you destroy the gameobject and instantiate a prefab without the applied changes?
i am unsure but it is fixed
{
if (_animator != null)
{
myCamera.Priority += camPriority;
uiManager.CrosshairAimed();
_animator.SetBool("isAim", true);
}
}
private void StopAimPlayer()
{
if (_animator != null)
{
myCamera.Priority -= camPriority;
uiManager.ResetCrosshair();
_animator.SetBool("isAim", false);
}
}```
I added a null check but now it works fine
might have been a prefab issue
really dont know
thank you tho guys
also check for script execution order
as some objects may load in before others
so make custom Start so the dependencies gets loaded in first
null check is bandaid to a bigger problem
are you talking about the static instance?
remove the null
and check again
might cause future headache if we patch things like that
yeah, currently it was in awake tho i remove the null and despite it being in start/awake, without that null check the error flags
im not spawning the prefab with the animator at any point
if you're doing UIManager.instance.Something in awake yes it will be null
because thats where you assigned the instance
or to my knowledge destroying it
uiManager = UIManager.instance;
is how i reference it
uiManager.ResetCrosshair();
for example
where is this called though ResetCrosshair
give full code
so this seems to be the main script causing the issue
the interesting thing is the same animator is being used by the player controller script
and the movement animations play fine, no null error
_animator.SetFloat("side", sideValue);```
seems to only be aiming
again, only when reloaded
your sub to those inputs look wrong
hello, I have encountered a problem can you help. My for loop returns 7 times and my value always returns 7 times 1 or 7 times 0 when I restart the project for example: 1 1 1 1 1 1 1 1 1. What I want is that my test value returns 1 or 0 7 times example: 1 0 1 1 0 1 1 1 1 0 like this. here
public void ValuesRandom() { for (int i = 0; i < damagedParts.Count; i++) { test = Random.Range(0, 2); } }
interesting how so
i’ve been having issues setting an animated tile back to its initial start frame. I’ve been trying Tilemap.SetAnimationTime(), but when I do, I see the tile flicker, but still end in the wrong frame.
Advice?
idk what is InputAction
ur overwriting the same value each iteration
InputAction is part of #🖱️┃input-system
wel diff values but same variable
missing index
what do I need to do
if test is string or array do test[i] where i is index
that wont work
test is int
what
I'll tell you what I'm trying to do.
so why is it not an array if you want 7 numbers
oh
You cannot assign when use indexer on string
so string is immutable in c#?
correct
I have car parts and I am trying to determine whether they are damaged or not, so I used bool and I will determine whether it is damaged or undamaged with random, this is the code I wrote.
`bool testbool;
int test;
public void ValuesRandom()
{
for (int i = 0; i < damagedParts.Count; i++)
{
test = Random.Range(0, 2);
}
for (int i = 0; i < damagedParts.Count; i++)
{
if (test == 0)
testbool = true;
else if (test == 1)
testbool = false;
damagedParts[i] = testbool;
}
}`
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
are you learning coding basics?
just set damaged directly on the parts during the loop
yeah
you dont need this int assigment at all
you need an array which is a series of numbers to store multiple numbers
nah you dont even need that
if the parts are already in array they should just have an isDamaged bool
yes but we need him to know how code works
an array of numbers would not serve any use here
they need to learn how to iterate through their carparts and assign the value depending on a random number
I think he is thinking that the 2 for loops are executed at same time
im junior dev this is my case a actually
code executes from top to bottom
dont think so
the logic is somewhat valid but not for 7 times
its test
again also doing 2 loops for that is unecessary
yeah i know im just testing
for (int i = 0; i < carParts.Count; i++)
{
carParts[i].isDamaged = Random.value >= 0.5f;
}```
anyway this should move to begginner
bro he is new take it easy with the logical thing
dont give him code teach him
nah i get it
i already explained it, and i provided an example..
Actually, I'm not very new, I just said yes to avoid beating around the bush.
you're def missing some basics on how the code is working
anyway I have 2 collider in the same object. How do I GetComponent<>() to one specific
you don't , you use the inspector
if the collider types are different then you find the specific type
yeah u right
what if my future enemy has a random number of child objects with colliders
how do I control it
you put them in an array of Colliders and you can loop through them
GetComponents is also a thing
okay nice
You could also create a component on the enemy that keeps track of one of them. Then make a public getter
yeah also an option
yeah, you need to use a monobehaviour to link them to specific variables for that
I’m trying to make a system where a front of ice/heat can propagate through a large tilemap of water/ice, affecting the nearest neighbor over time. Any suggestion on how to best represent/do this?
Also do we have some way of having code hierarchy in inspector
not really. treat a gameobject as having an unsorted collection of components
inspector for a given script shows different fields depending on the order of attributes you give.
I mean by script hierarcy like in go dot
example:
[Header(“Heading”)]
[SerializeField] private int jumpHeight;
public Collider2D playerCollider;
[field:Header(“Next section”)]
[field:SerializeField] public int autoProperty {get; private set;}
cellular automaton
no. in general, you do not want multiple components of the exact same type on a gameobject, unless 1) you have a script with specific references to each, or 2) you don’t care about identifying which is which
each gameobject is a "folder"
you can set a gameobject as a child of another gameobject
if that is what you mean
so I might have my player gameobject with a collider and player movement etc. Then a child gameobject might be a sword it is holding, which has its own collider and sword script.
but multiple components within the same gameobject are basically not sorted with any hierarchy
Godot enforces more hierarchy in that regard
Unity has a hierarchy of gameobjects, which contain scripts. Unity does not have a hierarchy of scripts.
Understand?
ye
I have a general concept question for a project I'm doing but not sure where to start.
I want to convert a video into a image sequence.
From that video sequence convert it to a sprite sheet.
Then apply that sprite sheet to a character
I know I can do this outside of Unity, but I want this entire process to work within my Unity Game.
Anyone got any ideas?
were you referring to me? or the other guy?
for this question
https://www.youtube.com/watch?v=5Ka3tbbT-9E
i have no idea why this vidoes appeared in my youtube home page but you can have a look
Download and play with this simulation here: https://tinyurl.com/43dzu9r5
Java Repository: https://tinyurl.com/88ndcdez
C++ Port Repository (In Progress): https://tinyurl.com/a246r6pp
Links:
All the old Java Applets: https://androdome.com/Sand/
Exploring the Tech of Noita: https://www.youtube.com/watch?v=prXuyMCgbTc&t=322s
Conways Game of Life...
use the video player
thanks
i think you can apply energy for each cell and simulate the transfer of energy in each tick
i’ll take a look at the vid later, when I have a break. In my case, I’m thinking about making the delay time a float.
one note is that it isn’t a state function. If I have water in contact with ice, the result is different if I’m propagating a freezing wave outward, of thawing wave
actually, I have an idea to use a separate grid. ty tina
Hey everyone, just working on optimising some code right now. I've found a section that updates a sprite every frame, however often it's just setting it back to the same sprite. I presume this has a performance cost associated with it, so I'm trying to figure out how to best improve this. Currently the code is as follows
sprite1
sprite2
if sprite != sprite1 && other condition
sprite = sprite1
else if sprite != sprite2
sprite = sprite2
Is there an even more performant way of doing this check? Obviously I'm comparing sprites, and I'm unsure if it just uses the memory address to check if the references are the same or if it's doing something heavier. I considered checking the name or the hash. What do you think?
I presume this has a performance cost associated with it
have you profiled it to see if there actually is a performance cost worth worrying about?
Well there is noticeable lag caused by this system on device, however I can't see anything particular in editor unfortunately. Because of this I'm working through the code just to see what could be causing potential issues with it
I should note that I'm shooting in the dark here because the profiler isn't providing any useful information about my situation
Or more likely I'm missing something
Also is it even worth getting the hash? I've just realised I could just as well use a bool
you have to profile, this alone wouldn't cause a major lag
I need to confirm it with my client tbh, he's the one complaining about it. I'll ask more questions and see
send them a dev build and you can also setup a remote profiling by IP connect
what is the other condition
just an int check if level >= level threshold
setting sprites isn't that costly
you can use switch instead but that would be premature optimization
It was being set in the update loop, so I figured it's definitely doing more than it needs to
an animation can even change sprites tens of time per second
true
Unfortunately I can't show the code. I don't reckon that is the issue anyway, I just wanted to know if/how much a difference it would make
I'm looking at some previous commits to see if anything jumps out at me. My biggest issue is not being able to replicate any performance issues on my end...
"I presume this has a performance cost to it"
This is literally the least productive way to do performance optimization. Your presumptions should never enter into the equation. Profile or you're wasting your time and ours
I appreciate the advice praetor, but you could phrase it nicer. If you read my other messages you'll see that I have profiled it, and it's not coming up with anything useful at the moment. The question was regarding how much of a performance cost that specific code had anyway, which has been answered. So thanks for your input
How does LogAssert.Expect() work with the Unity.Logging package?
The following code fails:
LogAssert.Expect(LogType.Log, "All allies are defeated");
combatLoop.EndOfTurn(); // runs Unity.Logging.Log.Info("All allies are defeated");
While this succeeds:
LogAssert.Expect(LogType.Log, "All allies are defeated");
Debug.Log("All allies are defeated");
I don't see this case mentioned in the Docs, and Google hasn't been helpful either.
In both cases, I see a Log appear in the Console
What does the success of failure message say? Are you sure it's not failing for some other reason ?
Fairly certain. The message is Expected log did not appear: [Log] All allies are defeated.
The only difference is the way it's logged (Debug.Log vs Log.Info). And I do see the Log.Info message in the Console, so I know it does get hit:
All allies are defeated
Logger:Log(LoggingLevel, String) (at Assets/Scripts/Logger.cs:29)
Battle.<AlliesAreDefeated>d__13:MoveNext() (at Assets/Scripts/Battle/CombatLoop.cs:159)
It does get called from an IEnumerator (CombatLoop start the Coroutine). Does that matter?
And the messages are identical; I've copy-pasted them over
What is Log.Info. Isn't LogAssert.Except expecting Debug.Log calls specifically?
It's from the Unity.Logging package. Full method call is Unity.Logging.Log.Info(string message);
And I don't know for sure if it is expecting *onl Debug.Log. The official documentation says:
"LogAssert lets you expect Unity log messages that would otherwise cause the test to fail. A test fails if Unity logs a message other than a regular log or warning message. Use LogAssert to check for an expected message in the log so that the test does not fail when Unity logs the message.
Use LogAssert.Expect before running the code under test, as the check for expected logs runs at the end of each frame.
A test also reports a failure, if an expected message does not appear, or if Unity does not log any regular log or warning messages."
I would expect it to work with the Unity.Logging package, but it seems like it doesn't
See what happens when you change to Debug.Log
I have, it works with Debug.Log.
Difference in message:
Log.Info:
All allies are defeated
Logger:Log(LoggingLevel, String) (at Assets/Scripts/Logger.cs:29)
Battle.<AlliesAreDefeated>d__13:MoveNext() (at Assets/Scripts/Battle/CombatLoop.cs:159)
Debug.Log
All allies are defeated
UnityEngine.Debug:Log (object)
Tests.Battle.CombatLoopTests/<Allies_Are_Defeated_Triggers_When_All_Allies_Are_Defeated>d__0:MoveNext () (at Assets/Play Tests/Battle/CombatLoopTests.cs:32)
UnityEngine.SetupCoroutine:InvokeMoveNext (System.Collections.IEnumerator,intptr)
I guess you have your answer then?
I can't really change the Logging in my game to Debug.Log. However, I would very much like to test whether messages appear in the Logging
I was wondering whether Log.Info can be made to work with LogAssert.Expect
gotcha I think I'm finally caught up on your original question 😆
Npnp
Ah, maybe Unity.Logging has its own Test package, I'll have a look
Yeah, found the answer:
It’s not natively supported by the Test Framework, a workaround is to use the WriteTo.UnityDebugLog sink at the cost of a negative performance impact.
Thanks for the help regardless, Praetor
hey i need to deserialize json formatted string into classes, but there is like 5 diffrent classes. How do I determine witch class to use? Every class has a "type" key (string)
thanks
you could deserialize twice once to a type that only contains the type fields so you can see it then choose the next time again
an other option is using something like this
https://github.com/manuc66/JsonSubTypes
wait
can I use something like
public class Base{
public string Type;
}
public class A : Base{
public float test;
}
[...]
you could, but you would still need to do things twice
first get base, figure out what type is, then choose your final type for the 2nd pass
ah yeah
ooh that can work thanks
which json lib were you using?
What means when NavMeshAgent.isOnNavMesh is true, but NavMeshAgent.navMeshOwner is false?
hey i need help with lighting...
whenever i try to build my game the lighting in the build is shutdown
how do i fix it ?
Are you using baked lighting?
im not sure what that means to be honest
You have realtime lighting and baked lighting. Baked lighting "bakes" the lighting data into the scene's textures. Realtime lighting allows for moving lights. If you're not bothered about performance you can make sure your lights are set to real time, otherwise go to Window>Lighting and bake the lighting into the scene
ok i will try that out now
thanks
hey i have script to move a navmesh agent to a position. Is it possible to assign multiple navMehAgents to one variable?
Sure, we call those collections. Some examples are arrays and lists.
For example you can have a List<NavMeshAgent> to store as many agents as you want.
i know that those exist but how do i change a navmeshagent into a navMeshAgent array?
you don't
you put a NavMeshAgent into an array
along with other agents
@hexed pecan COMPLETELY forgot to tell you both thank you. Turns out I just added a wrong script with a similar name to the component and not the script that inherits from IInteractable. smh.
how do i declare that the things in the list are navmeshagents?
List<NavMeshAgent> agents;
You are going back and forth between list and array. Pick one
thats what i did but then i cant call functions from the navmeshagent
sure you can
You can
once you have a reference to a specific agent you can call functions on it
you would need to get the specific agent you want out of the list and do what you want with it
If you want to do something to all of them, you can use a loop to iterate over all of them and do the same thing to each
thanks
Hi, I have some code to point a hose at a target point, but it's not quite doing it right, I have a player moving back and forth, their scale x is 1 or -1, when it's -1, the aim is off a bit and I don't know why
var AngleDeg = Mathf.Rad2Deg * AngleRad * tank.transform.localScale.x;
hose.transform.rotation = Quaternion.Euler(0, 0, AngleDeg);```
for unity netcode i have three two different ui, one for the gameMaster and one for each player,
im unsure how to give players their own seprate ui because their uis keep overlaping
thanks
Hey! I'm trying to make a button open my SettingsPanel, but when I attach my script to the buttons "OnClick" event I don't see my Open and Close functions in the function drop down menu.
What could be causing this?
You need to attach a gameobject that has this script as a component, not the script itself
OH, thank you so much lol
any idea how can i code a script that will always keep a folder opened in assets inspector window? (not the inspector, just the unity's file window)
maybe if theres a callback whenever you click on files
then i could check if its opened there, if not then open
idk if theres even api to do this
like keep a specific folder open?
ye like they close sometimes
for example keep this always open (so that its children are visible in the folder tree)
Is there any suggestions on how to make multiple objects move as one until a specific action is done and then make only some of the objects start moving seperatly?
parent them all under one gameobject, then when specific action is done swap some to a different parent
Should have specified that objects are physics based or will work either way?
Physics objects dont really work too well with parenting. What's the use case?
making walls ig
that can be broken down
Keep the rigidbodies on the pieces kinematic then when they are hit set them to non kinematic and detach them from the parent
That would be the simplest option. Now if we are talking actual demolition there a bunch more work to be done on clustering, separation, structural integrity and so on.
Ie if you don’t want floating pieces
Broken like piece by piece? Or damage any piece of a wall and then it all breaks?
What Uri said above works for piece by piece. If you want to destroy the whole thing I'd just have it as one object and replace the whole wall with a destroyed version when it should break
broken into like cubes/parts
ig it will work in a way kind of
why when you change a cinemachines follow target in code it will stay like that but if u change it in an animation it doesnt work
Say I have something like this
[Serializable]
public class Wave
{
[SerializeField]
private float duration = 60f;
[SerializeField]
private float cutOff = 0.3f;
[SerializeField]
private int maxValue = 10;
[SerializeField]
[Range(0.1f, 10f)]
private float noiseScale = 1f;
}
Then, in another class, I serialize a list of the "Wave" above. When I add a new instance to the list via the inspector, it's added with default values rather than the ones defined above / the standard behaviour when adding components.
How can I make sure new instances are added with the values defined in the class?
hey, when I slow down game scale Time.timeScale = 0.1f; whole game is snapping, can I somehow change physics update interval?
it's not smooth at all
fixed, found it in project settings > time
Hey, I have a little problem. I have a hex grid system, with a pathfinding system. My list of tiles for a path is given correctly. I wanna add some directional arrows to show the path on the tiles. the arrow is just a sprite renderer (it's in 3D). I tried everything to rotate the arrow at index N to the tile at N+1, but it never works, does anyone could help me please? 🙂
Hi, could you provide your current code for the arrow rotation
Sure, I'll give you that
I tried this
public void ShowArrowTowards(Tile tile)
{
Vector3 direction = (tile.transform.position - transform.position).normalized;
this.displayInformationRenderer.sprite = arrowSprite;
if (direction != Vector3.zero)
{
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
angle -= 90f;
displayInformationRenderer.transform.rotation = Quaternion.Euler(0f, 0f, angle);
}
}
I also tried transform.Rotate(); transform.LookAt(); transform.eulerAngles = new Vector3(..)
I never found a solution on internet lmao
and what are you seeing ? no rotation or incorrect rotation ?
Incorrect rotation, let me show you what that code gives me
the arrows are... really facing up. However, if i took one in the scene, and just set rotation to (0f, 0f) on x and y, and manually change the z value, it rotates well, so that's why I tried to do
Quaternion.Euler(0f, 0f, angle);
This is the rotation given by the inspector
idk why it gives me this, but... yeah
and on the picture you set the arrows to indicate toward which direction ?
Maybe set the local rotation if you want the inspector to match?
Each arrow has to indicate towards the next tile, i tried to raycast to see the path, and it goes well, but not the rotation
Don't look at the inspector and assume it's going to be the same value you set it code. Euler angles derived from quaternions can be different representations of the same orientation
Else print the rotation in euler and ignore the inspector value
Okay i see
I tried, but let me retry
I don't think you'll get what you want but maybe it'll be a bit more understandable from the inspector relative to location rotation.
fact yup, now we can see flat arrows, but as u said, they're not facing to the next tile
that's completely weird, because I'm taking Atan2 of the direction, so it has to get the good value tbh
Log the result and values to see if they're what you're expecting.
Were you feeding arc tan directions?
I don't really understand ^^'
I'm doing some raycasting and printing values, but to be honest for the first arrow, it has to be approximatively 120 in Z axis, but it returns me 90
Ah nevermind
The raycast of the direction is correct, as u can see
Was the direction vector as expected for each?
yeah
You should be able to visually confirm
the direction is as expected yeah
So the resulting angle isn't?
yeah
that's the problem, and a weird one
maybe i'm not using the Mathf.Atan2 correctly, i'm not kinda good at math
The value would be in radians. Is that what you're expecting?
Returns the arc-tangent of f - the angle in radians whose tangent is f.
https://docs.unity3d.com/ScriptReference/Mathf.Atan2.html
Ah, I'm on mobile. The screen is small.
sorry :/
i just saw something on a website which tells me that it can be caused by the values passed in mathf.atan2
Can you log the direction vector and the resulting angle?
They're using Mathf.Atan2(-direction.y, direction.x) instead of Mathf.Atan2(direction.y, direction.x), i'm gonna use that
sure
Showing us the console log, if possible.
yeah yeah np
I tried to put -direction.y to try as well
and just so you know, i just do angle -= 90f, as well so if u want the real result of Atan2, you'll have to add 90
arctan(z, x)
let me try,
also if you just want the sprite's Y axis to point at the position, just assign its transform.up to the direction. no need for the atan2
how do you do that?
displayInformationRenderer.transform.up = direction
now we have something interesting
I'm gonna try your thing instead @somber nacelle
tbh i didn't even know that we can change transform.up
that's weird
There seems to be a pattern 
yep, maybe the -90f is useless now, or maybe use -direction.z instead of direction.z
show the current code
or invert, i'm gonna try all possibilities
public void ShowArrowTowards(Tile tile)
{
Vector3 direction = (tile.transform.position - transform.position).normalized;
this.displayInformationRenderer.sprite = arrowSprite;
Debug.DrawLine(GetDisplayRenderer().position, tile.GetDisplayRenderer().position, Color.red);
if (direction != Vector3.zero)
{
float angle = Mathf.Atan2(direction.z, direction.x) * Mathf.Rad2Deg;
angle -= 90f;
Debug.Log("direction vector = " + direction + " | angle = " + angle);
displayInformationRenderer.transform.localRotation = Quaternion.Euler(0f, 0f, angle);
// displayInformationRenderer.transform.up = direction;
}
}
That code is for the first screenshot
And if you want the code for the 2nd one, just inverse the comment and code in the if statement lmao
i tried -direction.z, direction.x and i got this, i think if i delete the -=90f, it could work
it works !!!! let's go thank you guys
it tooks me a few hours to come here because i thought i could resolve it xD
hi guys
i have a bit of a problem
im making a minecraft inv system and its pretty much a copy
but theres a problem on the right click
dammit
how do i upload a small vid showing whats off
Mp4 under 8mb
why are my npcs not dragging into this room? https://hatebin.com/nmvvkbwhyp
hello there!
i got a problem with reading a json file
its especially about this part
{
"possibleMoves": [
["E4", "E5"],
["A2", "A3", "A4"],
["B2", "B3", "B4"],
["C2", "C3", "C4"],
["D2", "D3", "D4", "E3"],
["F2", "F3", "F4", "E3"],
["G2", "G3", "G4"],
["H2", "H3", "H4"],
["B1", "A3", "C3"],
["D1", "E2", "F3", "G4", "H5"],
["E1", "E2"],
["F1", "E2", "D3", "C4", "B5", "A6"],
["G1", "E2", "F3", "H3"]
]
}
the class im trying to get it into looks like this
[Serializable]
public class ChessData
{
public string date;
public string result;
public string site;
public string white;
public string moveSuggestion;
public List<List<string>> possibleMoves = new List<List<string>>();
public string promoteTo;
public string black;
public string history;
public string @event;
public List<OccurredPosition> occurredPositions;
public string FEN;
}
it doesnt throw any errors but just cant read the content, does anyone know how to get it working?
if i try it with logs it give me 13 empty lists
why are you using a raycast with 0 direction? just use OverlapPoint instead. you probably want to use a layermask for the query though because its probably detecting the NPC
unity's JsonUtility does not support deserializing multidimensional/jagged arrays and lists
is there a way arround that?
or only possibility to adjust the format of the JSON?
Maybe use a List of a class that u create by urself and use [System.Serializable] on top of it
you could use Json.NET instead or just don't have nested lists
i think i might just go with not having nested lists then, ty for fast answer
Np
how many people use giant switch case blocks for logic?
i try to avoid that as much as I can, and use delegates, but I feel like I should just use switch case more liberally
usually up to 5 then I break it more into sub-types / sub-states
like what it switching on?
if its just a enum, and its getting big you can just pass functions around directly, or use a interface type
when I say giant switch case blocks, I mean 20+. It doesn’t depend. You do this, or you don’t.
What are you gonna do with that information though?😅
20 is still in the it depends region it really depends on what its for
what you are switching on and why
like if its a switch over enums, and the enums are only used for choosing what logic to run
would just pass functions directly in that case, or a object that has overriden methods
really most questions like this come down to use what works for you in the moment, and if you start feeling a lot of friction doing that figure out why and come up with a new approach
it’s a poll
reading the room
If you're looking for justification to keep your current method, maybe start look at redesigning.
Out of like 100 scripts I have, I think I used a switch once on an enum with 5 options. Having to do this often sounds like a design issue
my personal limit on switch case blocks is 6
but i see some people writing some giant goddamn switch case blocks, and I want to know how common of a practice it is
how does a loop replace a switch case, my man
a loop with conditional ifs and an array of constants
What on earth..
if the conditions have a pattern better code that way
maybe help me out. I have this code:
switch (cardType) {
case “PotOfGreed”: hand.size += 2; break;
case “Cow” : milk++; break;
case “Corn”: player.health++; break;
…
}
how does this turn into a loop
you dont code it that way
no. you said to learn how loops work
no. you said to learn how loops work. Now you teach how loops fix this issue
these dont have any patterns
i was working with a guy the other day with a switch-case block with >120 cases
that would be hard to read
trying to get him to something not cursed. and I want to know how common that practice is
i dont think anyone would want to go through all of that
just interface ICardEffects and executeEffects()
I tried to guide him towards that, but he’s on GDScript, which lacks interface support.
So that is not an option
you could try abstract classes
that’s what I was leaning towards.
anyway, point being, I want to know if there are any more degenerates out there
writing giant switch case blocks
yes my friend bruteforced 100 if else to solve a problem for kindergartens that only requires 5 lines
Even with the interfaces or abstract class, you lose out on some ease of setting things up in inspector. Now you have to do some custom editor stuff
i think the core question is to tie a specific enum to a particular function
I mean if its card effect, it only affect one of the two player right?
i already sketched out a solution for him a while back
abstract class was my main recommendation
he did not like the idea of defining 120 different classes
you still need a way to tie the delegate to the key/enum
repeated actions on cards can be reduced to AddCard(), FindCard(), DestroyCard(), BanishCard()
most yugioh effects can be reduced to about 20-30 functions
they summon bunch of stuffs and do random things
🤷♂️ depending on the work being done and the quality of work expected, i wouldnt want to do this either. Sure you can make a bunch of poco and just save time by putting them in 1 file but whats the difference at the end of the day
only thing that matters is how this affects the users experience
tie the delegate to key/num. I dont really know what you are meaning and have never done such thing. Can you explain it?
why must we have key and enum
like Dictionary?
https://hatebin.com/nreyklblta Why is the npc still not entering the room? i changed my code
you're still not bothering to use a layermask like i suggested before so your OverlapPoint is likely just detecting the npc object instead of the room object
Honestly, I don't think I use switch case at all . . .
what is a layermask?
so would i use the laymask with overlappoint?
Yes
ok let me try agin
Hi guys I have a moving platform and I want the player to move alongside the platform.
To achieve this, I parent/unparent the player to the platform.
However, and here's my question: When the platform is moving (XYZ) the character controller and camera are rather "janky" and dont' move/flow smoothly they instead jitter with the platform.
Anything I should consider when trying to achieve a smooth look for this?
How are you moving the platform?
Spring joints
moving the platform
I was thinking, add the velocity of the object to the controller.Move() method
Spring Joints
That would be the proper way
Spring joints don't move anything afaik. They connect 2 rb or an rb to a static point.
Thanks, due to the volatile nature of the spring joint bridge, I think this coupled with setting the parent of the player to the bridge itself
would solve the issue
You dont parent when you set the velocity
Oh, really?
Have a externalVelocity variable in your character. Then in your update resolve it and add it to your move after you have calculated player input. Then add the end of the frame 0 it out.
This away any number of objects can add do this external velocity during the frame
How would I go about copying the angular velocity and velocity of one rb2d to another? I can use addforce for the velocity but with addtorque the pivot point is different
first.velocity = second.velocity
first.angularVelocity = second.angularVelocity
Is it bad to have a ton of serialized fields in something like a title screen
If you need them, then you need them. Any alternative would either be convulated or through a worse method like .Find
Is using AIModules preferred or should I build my own AI algorithms
just asking for your general preferences
What is AIModules?
For Ui I prefer loose coupling via events
like built in packages from Unity to support AI
I would like to build more lively AI like in RainWorld
is there a way to work around enum's lack of compatablility with inheritance?
just dont use Enum then
alr
Right got it Ty
loose coupling?
Unity’s build in package offers a solution for AI navigation. You build your own behaviour how you like.
For example the game has a OnHealthChanged event that broadcasts the new value. The ui healthbar subscribes to that event via a component and updates its text or image or what ever.
would trying to instantiate multiple enemy prefabs with one object name for an enemy class break the game?
i don't know if there is functionality to generate new names if it wont work
gameobjects can have same name
What the heck naming convention is this? Vector3 m_Movement; it is in an official Unity Tutorial
Oh, it goes on to 'explain' the reasoning behind it. well, i won't be using that one :/ i get it, but a bit too much clarification for me. I will do Vector3 _movement though
if any of you more experienced people think i Should be following that convention, please let me know
you dont need to follow any naming convention for you own personal project
indeed
Hungarian notation https://en.m.wikipedia.org/wiki/Hungarian_notation#Examples
Hungarian notation is an identifier naming convention in computer programming in which the name of a variable or function indicates its intention or kind, or in some dialects, its type. The original Hungarian notation uses only intention or kind in its naming convention and is sometimes called Apps Hungarian as it became popular in the Microsoft...
son of a gun! thanks. i did not realize it was an established convention. I thought they were just kind of winging it in the early days of Unity
hungarian notation is actually kinda useful
in projects with multiple people of course
makes sense. hmm ok, i will consider trying to develop the habit, for when i Do work with others
well you shouldn't adopt it in a lot of cases
yeah, i do see a lot of disadvantages, even listed in the wiki
It is widely adopted by the c/c++ devs. Since most unity devs are from that backgroubd use the languages daily they default to it in c# as well. How er Microsoft have a different convention for c#
The C# coding conventions are pinned to this channel
I just used it because competitive programming used to be single letters variable then we had to work in teams
I have a terrible habit of forgetting pinned messages exist :/ thanks
single letter variables would drive me insane 
could someone help explain what went wrong here?
it dosen't seem like anything was wrong with my code
i was using scriptable objects
look like you are missing some using statements
your ide should be full of red ink
it is not at all
everything seems valid
screenshot your ide with one of those scripts open
both here
so you are missing a using just like the errors tell you
which one would it be though?
duh
how are you actually supposed to parent a child ghost entity to a parent ghost entity in dots netcode? adding a parent component to the child and setting it after instantiation causes the parent component to not make it to the other side
which ide is that?
visual studios
open the Solution Explorer tab and screenshot again
are you trying to build in the ide?
but Unity doesn't work like that, it takes care of compilation
yes
i dont see it anywhere
View->Solution Explorer
straight up missing
and now?
screenshot the ide again
which OS is this, coz that does not look right at all
mac
how do you open a script?
double clicking the file
ok, close your ide and in unity right click in Project view and then open c# project
your Solution Explorer should look something like this
im getting more ledgible error messages
so you have script errors, fix them
Is VS even available on Mac?🤔
fixed and still broken
Ctrl+S to save
save all the files
also this should move to #💻┃code-beginner
Where do you see these errors? In the ide?
ye
did you save all the changes?
been saved
What IDE is that? If the same errors don't appear in unity, then the ide is not configured correctly.
Then something broke. I've no clue how to configure the ide on Mac, so, can't really confirm if you did it right.🤔
VS for Mac is practically a completely different program from VS for Windows and it doesn't work very well with Unity. And MS is killing it, it's end-of-lifing this year. Practically the viable options on Mac are VSCode or Rider
ty that is actually very helpful
how do you get to this scene with a remove button
i only see this import and redownload shit
This simply means that you didn't import it so there's nothing to remove
You've only downloaded the package, but didn't include it into the project
No, the files are in the damn project
I'm sorry for being so fucking mad but it's like 1 am and I've been debugging for 5 fucking hours
i think you cannot remove stuff from that page. I remember having to hide it from the asset store website
I don't think he wants to hide the package from the package manager
I want to delete the package that I guarantee you I've imported into the code
Because the very files are there, and I tried to delete the steam VR files but there's residue shit in program files and whatnot
then delete it from the assets folder
And it's breaking the damn project
I did. There's residue
program files 🤔
Bro I don't fucking know what it's called Jesus Christ
Again sorry for being so mad but I would really love to sleep for my damn 8 ams
Why unity gotta be so damn STUPID sometimes
Probably a wild guess, but did you try accessing it from Packages: In Project ?
The what?
Package Manager, top left, second option, change to In Project
Oh bruh
my assets/in project
oh someone already replied
XD
i want to convert a face picture into 3d model with body , just like Readyplayerme . however i want more realistic textures of the body and face
I'm using visual studio code, and did an update to an extension, really no clue which it was, and suddenly all of my code predictions are gone. How do I fix this?
Take a screenshot of your vs window with a script open.
Oh, vsc. My bad. Thought it was vs.
It works for a split second and I can see everything in the correct color then it just disapears..
The best I can suggest is check the config guide again:
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Could be the C# plugin
It was that last time so ima go to an old version
and try
I did but I think it broke mid way through version change..
going back a month changed nothin
I've been coding for at least 5-6 years on many different software but nothing has brought me closer to quitting than stupid vsc breaking every time I update literally anything.
This doesnt help, the vsc page just explains how to set your editor as vsc which Ive done.
why cant i have nice things
thx for trying to help tho
Just wait
My vsc didn’t work at first (after the new extension published) and one day it came back
thats good
I am playing around with 360 videos, just need one cubemap video to test... and no idea where to get a sample. The Unity Interactive 360 sample project no longer exists on the asset store...
- I'm making a renderer wrapper that allows to add and remove transforms to render meshes at via underlying implementations. The transforms are going to enter and leave in a large loads at once, and will be slowly removed in between. What would be the best data sctructure to accomplish this? Approximate numbers are 8-24k transforms at once
A list🤔
- That's what i'm going for rn. It's good for insertion but horrible at removing, especially when it needs to shift that many items
does it ordered or not
- Ordering gives faster lookup, but i'm trying to figure my way around any need to lookup the presence of the transform before adding/removing it. In a nutshell, it doesn't matter for now
- Most likely i'll figure it out
8-24k is not large for maintaining an additional hash table for Transform
btw you dont need to shift the list, just replace it with the last one then pop the last
- I was talking about the built-in list. But yeah, i can work it around to remove items manually and not with its method
so dont use built in method if it is not fast enough
Hey, someone here who knows about unity ads?
They work 100% fine in the editor, but on mobile not. I narrowed down that the ads fail to load, but I dont know further. Anyone here that can help me? Thank you
If I cast IEnumerable<ClassNameHere> of a List<ClassNameHere> as (ClassNameHere), does it create a new instance of the class, or is the new variable still going to refer to the one in the list?
if i understand correctly IEnumarable<> stores the position of an instance inside a List. if that's the case what's the proper way to get the actual reference to the instance from it?
Edit: Nevermind, dumb mistake
hey i need help with unity relay, when i open another scene additivly, because the player is not moving, when i return to the game scene the player would have been disconnected because of inactivity
how do i fix it ?
Your best bet is to ask in #archived-unity-gaming-services, Unity staff frequent that channel as well.
Hey guys.
How can i make a good RIGIDBODY fps player controller, that can go up slopes and terrain?
I have a limitation have however:
-i need other forces to take effect on player, such as explosions and etc for rocket jumping, so i can NOT directly set velocity to player input.
Any good guides for this out there that go over how to handle slopes and terrain? When normally rb charachter controllers bump into slopes and then get launched off of them.
Remember, i need to have rocket jumping so I CANNOT CLAMP OR DIRECTLY SET THE VELOCITY ON ANY OF THE AXIS
I'm sure you can find tutorials online for this. You have to add forces along the slope of the ground below the character, not directly forward like most people do.
i would use KCC
kinematic character controller plugin
You just said kinematic
i did?
I said i want external forces to move my player around
KCC respects collisions
do you mean you want to actually use .AddForce
which can be easily simulated on a kinematic body
Yea
How?
Do i need to calculate the velocity and drag myself?
the whole point of KCC is to make a kinematic RB move in 3D while respecting collisions vs static and kinematic rigidbodies
AddForce is literally velocity += deltaTime * force / mass
but depending on 2D or 3D changes when the velocity += is evaluated.
dosnt the fact that this is kinematic mean it can push physics objects of any mass without being slowed down?
that is what KCC is for
KCC is more like a custom physics solver
But i dont want my 40kg player to be able to push a 1000kg rotating gate
I made my own physics engine similar to KCC for 2D. It took me 3 months, and I’m already very comfortable with all the math. You do not want to make your own engine.
KCC solves the physics to not have that happen
just look at the main video for it
So it will all be nornal? No weird interactions with physics objects? Its all be done beforehand?
I just need to implement addforce?
Showcase for the Kinematic Character Controller system
Available now on the Unity Asset Store: https://www.assetstore.unity3d.com/#!/content/99131
Forum thread: https://forum.unity.com/threads/released-kinematic-character-controller.497979/
Browser demo: https://phil-sa.itch.io/kinematiccharactercontroller?secret=rjRvT8GfZCAXEkevCF92TV07UQ
Musi...
just look at what it does
Yooo this is amazing. It even has stairs and steps implemented
I wont need to clip stairs with slopes!
I cant believe its free
KCC is like its own mini physics engine
it does require your own implementation. it’s like a separate rigidbody-like API
like you need to tell the KCC where to walk etc, but most of the slopes/stairs/collision/etc is what you are getting in the package.
it has a big document on how it works in detail
Thank you 🙏
👍
I dont have to reimplement my own charachter controller for the fourth time!
Ive tried making charachter controllers with the built in component, kinematic rb's, and non kinematic rb's and ive never been able to make any of them work well.
whats the client equivalent for
if UNITY_SERVER
?
Hello guys. how are you?
#if !UNITY_SERVER
makes sense
how to not destory object when owner out in photon fusion?
I would like to help senior guys..
go ask in photon discord
where is photon discord?
idk
@scarlet viper Could you invite em?
its pinned in #archived-networking
i got a var set to the type of a struct
i want to check if the var is set or still empty, but VS doesnt let me do a null check, why ?
does "set to the type of a struct" mean that the variable's type is the struct or that it stores the GetType of a struct?
private myStruct varName;```
first
Struct values can't be null
so the var holds a struct with the default values ?
also :
why cant struct in chsarp have default values ?
it can
they (class members) have default value
yes, but I cant set a custom one
it will be the defautl chsarp one
int will be O
cant say its 5 "by default"
yes
why is that ?
if i remember correctly in cpp you can, what's the tech difference that allows cpp to do so
of course you can set a struct int member to have a default value of 5
i had a null reference error i was tackling yesterday on the discord with the help of some others to which no conclusion was really indentified
in the end, I updated mt 'Version Control' package and the error just.. fixed?
anyone know why this may be the case?
whats the synthax ?
isnt that a newer c# feature?
public struct S{
int x=5;//not support
}
struct MyStruct { int x=5; }
Ignoring that int is not a struct, being able to set the default values of built-in types would be handing you the world's biggest footgun
does this trick works in the c# version unity is using ?
public struct MyStruct
{
int? myInt;
public int MyInt { get { return myInt ?? 42; } set { myInt = value; } }
}
here the "default value" would be 42 until assigned
if (!myInt.HasValue())
checking your nullable int
okay
really all int? is doing is adding another bool to the struct
a bool to the struct, or to the int var ?
to the int var but as the int var is part of the struct to that as well
okay
so here i could make my struct var nullable ?
is this permited ?
yes
private myStruct? varName;```
== null wont work ?
maybe, I always use HasValue
well now VS tells me that I cant access my struct members
cast myStruct? to myStruct ?
had to use Value
i guess it needs to check if my var isnt null before getting its members
Test your C# code online with .NET Fiddle code editor.
makes sense
another question,
private IEnumerator MainLoadAsyncScene(string choosenScene)
{
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(choosenScene, LoadSceneMode.Additive);
_isAsyncLoadingBigBackground = true;
while (!asyncLoad.isDone)
{
yield return null;
}
_isAsyncLoadingBigBackground = false;
}
private void LoadAsyncScene(string choosenScene, LoadAsyncEndedDelegate sceneLoadCallback = null, int sceneLoadCallbackValue = 0)
{
StartCoroutine(MainLoadAsyncScene(choosenScene));
// will this code only be executed when "MainLoadAsyncScene" ended the while loop ?
no, the first time yield return null is executed
nothing waits after startcoroutine only inside the while loop
okay
could I run LoadAsyncScene as a IEnumerator
nah this wont solve my issue
how could I make LoadAsyncScene wait for MainLoadAsyncScene
private IEnumerator MainLoadAsyncScene()
{
while (!asyncLoad.isDone)
{
yield return null;
}
}
// StartCoroutine(LoadAsyncScene());
private IEnumerator LoadAsyncScene()
{
yield return StartCoroutine(MainLoadAsyncScene(choosenScene));
something like that I imagine
dont, pass your delegate to the coroutine and let that call it on completion
i call later, after some code finished executed after the load
its not a delegate i call right after the load
sorry, the name is misleading
that will work
great, ty
this shit can get real complicated real fast, so take care
i'll do my best
private IEnumerator MainLoadAsyncScene(string choosenScene, Action<LoadAsyncEndedDelegate> callback, LoadAsyncEndedDelegate sceneLoadCallback)
{
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(choosenScene, LoadSceneMode.Additive);
_isAsyncLoadingBigBackground = true;
while (!asyncLoad.isDone)
{
yield return null;
}
_isAsyncLoadingBigBackground = false;
callback(sceneLoadCallback);
}
private void LoadAsyncScene(string choosenScene, LoadAsyncEndedDelegate sceneLoadCallback = null, int sceneLoadCallbackValue = 0)
{
StartCoroutine(MainLoadAsyncScene(choosenScene, LoadCallBack, sceneLoadCallback));
}
void LoadCallBack(LoadAsyncEndedDelegate sceneLoadCallback) {
// Do Stuff
sceneLoadCallback();
}}
for example
and even harder to follow and debug
so you can't do this, but there is another option
public IEnumerator TopLevel() {
yield return InnerCoroutine();
Debug.Log("It is done");
}
IEnumerator InnerCoroutine() {
while (Time.time < 10) {
yield return null;
}
}
tbh, since i only need this for 2 things, i just duplicated the following in 2 different fucntions
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(choosenScene, LoadSceneMode.Additive);
_isAsyncLoadingBigBackground = true;
while (!asyncLoad.isDone)
{
yield return null;
}
_isAsyncLoadingBigBackground = false;
Fen, this the same right ?
When you yield an IEnumerator from a coroutine method, Unity will repeatedly call MoveNext() on the enumerator you yielded until it's exhausted
im returning the yield return of a inner coroutine
then it'll go back to calling MoveNext() on the original enumerator
ah, yes, there you go
This is a close recreation of how you'd usually write async code
which I think is a lot easier to parse than Callback Hell
wait i just saw that you arent using StartCoroutine to call the InnerCoroutine
is it because its already in a coroutine ?
Hm, I'm actually not sure! I think the outcome will be the same..
StartCoroutine returns a Coroutine object
i'll keep my start method in case
The StartCoroutine method returns upon the first yield return, however you can yield the result, which waits until the coroutine has finished execution. There is no guarantee coroutines end in the same order they started, even if they finish in the same frame.
now I need to check if yielding an IEnumerator does what I think it does
(i.e. the same thing as yielding a coroutine object)
excellent, it does
great
I'm not sure if they're absolutely identical behind the scenes
there's certainly a huge difference if you don't yield the object
IEnumerator Foo() {
StartCoroutine(Bar());
Debug.Log("Hi");
}
IEnumerator Bar() {
yield return new WaitForSeconds(1f);
Debug.Log("Hi again");
}
This immediately prints "Hi", then prints "Hi again" after one second
IEnumerator Foo() {
Bar();
Debug.Log("Hi");
}
IEnumerator Bar() {
yield return new WaitForSeconds(1f);
Debug.Log("Hi again");
}
This prints "Hi" immediately and does nothing else
IEnumerator Foo() {
yield return StartCoroutine(Bar());
Debug.Log("Hi");
}
IEnumerator Bar() {
yield return new WaitForSeconds(1f);
Debug.Log("Hi again");
}
This prints "Hi again" after one second, followed immediately by "Hi"
for all examples, you are doing StartCoroutine(Foo()) right ?
Immediately print "Hi", then print "Hi again" after 1 second
Immediately print "Hi"
Print "Hi again" after 1 second

An IEnumerator-returning method executes until it hits a yield and then stops
If you don't call MoveNext() on the resulting IEnumerator object, it will do nothing more
because it's patiently waiting for you to ask for more values!
so using StartCoroutine makes it automatically call MoveNext ?
I think it's useful to understand exactly how enumerators work. It takes away a lot of the "magic" from Unity coroutines.
Yeah. StartCoroutine is an instance method on MonoBehaviour (or was it Component?)
yes it is intersting
When you call it, the IEnumerator is stuck into a list, and every frame (by default), every enumerator in the list gets MoveNext() called on it
okay i got it
okay, yeah, it is on MonoBehaviour
This can also be a source of slight error
without starting a coroutine, when calling a IEnumertor, it will stop at the first yield return, and wont try again (thats when you use MoveNext)
IEnumerator DoStuff() {
while (true) {
Debug.Log("Doing work");
yield return null;
}
}
This runs twice on the frame that you start it
thats why sometimes i was seeing some errors at MoveNext, i was wondering what was this method i didnt write
It hits Debug.Log once as it starts executing
then it yields and DoStuff() returns an IEnumerator
then Unity calls MoveNext on it in the same frame
unity calls once MoveNext ?
It calls MoveNext every frame, unless you yield something like WaitForSeconds
no, I'm talking about when you run StartCoroutine(DoStuff())
also, uh oh, I'm double-checking and I might be wrong here 🫠
one moment
ah, I was wrong about that! Unity waits until the next frame.
I was expecting to see two "Doing work on 86" messages in the console.
(frame 86, that is)
The first message comes from where we actually called DoStuff(); the rest come from Unity's coroutine logic
okay ty
...uh oh, am i wrong about something else here, too
now it way more clear
today is a learning experience
:(
Initially, the enumerator is positioned before the first element in the collection. You must call the MoveNext method to advance the enumerator to the first element of the collection before reading the value of Current; otherwise, Current is undefined.
Ooooooooooooooohhh
So I was wrong all along. When you run a method that returns IEnumerator, nothing happens.
StartCoroutine immediately calls MoveNext()
That's why I thought it ran up until the first yield statement.
Shoot. That's embarrassing
Well, at lesat I know now!
from memory, when i forget to add StartCoroutine, nothing happened.
thats why i thought it was weird
with that in mind, all three of these would do absolutely nothing!
so i have to keep my yield return StartCoroutine(...);
the punchline: you can do it either way
you're yielding a value to Unity here
if it sees you yielding an IEnumerator, it will start working its way through that enumerator
if it sees you yielding a Coroutine, it will wait until that coroutine is done
I don't know if it actually starts a second coroutine in this case.
or if it's just equivalent to...
IEnumerator enumerator = InnerMethod();
while (enumerator.MoveNext())
yield return enumerator.Current;
That's something worth looking into
i think it just extends when you arent calling a new coutine in a already executing ones
...maybe in a separate project. i've just littered my game with random coroutine garbage, haha
"oh, more code to explore with MoveNext !"
i have no idea how i missed that for this long.