#💻┃code-beginner
1 messages · Page 841 of 1
I mean, I guess?
you get a float, and if it's positive, that refers to the right direction, and if it's negative, it's leftwards (by convention in unity)
changing input systems only changes that very first part, getting the float
show us how you are moving the character
yes, I want to get the float, I don't know how to
public class PlayerMovement : MonoBehaviour
{
public float velocidadeMovimento = 20f;
private Rigidbody2D rb;
private SpriteRenderer spr;
private Vector2 direcaoMovimento;
private InputAction iact;
void Start()
{
rb = GetComponent<Rigidbody2D>();
spr = GetComponent<SpriteRenderer>();
iact = InputSystem.actions.FindAction("Move");
}
// Update is called once per frame
void Update()
{
rb.linearVelocity = direcaoMovimento * velocidadeMovimento;
rb.linearVelocityY = -velocidadeMovimento;
if ()
{
spr.flipX = false;
} else if ()
{
spr.flipX = true;
}
}
public void movimento (InputAction.CallbackContext context)
{
direcaoMovimento = context.ReadValue<Vector2>();
}
}
a Vector2 is made of two parts: X and Y
the second linearVelocity is to make the character fall, idk if it's the best way of doing that but it was the one I found
e.g. direcaoMovimento.x is the horizontal part of the player's input
direcaoMovimento here is as if you had direcaoMivomento = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical"))
yea it works
is there a better way to make the character fall then the rb.linearVelocityY with the negative movement speed?
this being in side-scroller view?
Yes
how do I do this?
well.. you would only assign the X velocity, like how you're only assigning the Y velocity on the second line there
ah, okay
you might also want to change your input actions to be a 1D input, if you only use horizontal input (though there are considerations to be made there regarding how you want to control your player overall - how jumping works, what W/S do, etc)
you mean only having the horizontal movement buttons in the action input editor?
yes
sure
well, the velocity of the X axis is the first rb.linearvelocity
also, if there a way to force Unity to recompile stuff? Because most of the time it doesn't when I make a change to the code in the script
it's also assignable via rb.linearVelocityX, like you're doing so with Y
make sure to save
I saw, but kinda pointless, but the issue is without the linearvelocityY the character falls too slowly, I could just make the gravity very high but it kinda feels like a weird way to do that
I do save, it still doesn't do it all the time
make sure your characters are sized properly
oh and make sure you aren't resetting the Y velocity to 0 in some way
what's your current code?
It would compile every time unless you've disabled it. The frequent Unity "hold on" message would indicate this.
what platform are you on? i recall linux reportedly having some watch issues
What you mean?
Linux
public class PlayerMovement : MonoBehaviour
{
public float velocidadeMovimento = 20f;
private Rigidbody2D rb;
private SpriteRenderer spr;
private Vector2 direcaoMovimento;
void Start()
{
rb = GetComponent<Rigidbody2D>();
spr = GetComponent<SpriteRenderer>();
}
void Update()
{
rb.linearVelocity = direcaoMovimento * velocidadeMovimento;
rb.linearVelocityY = -velocidadeMovimento;
if (direcaoMovimento.x > 0)
{
spr.flipX = false;
} else if (direcaoMovimento.x < 0)
{
spr.flipX = true;
}
}
public void movimento (InputAction.CallbackContext context)
{
direcaoMovimento = context.ReadValue<Vector2>();
}
}
make sure they aren't like, overly big. that could cause them to appear to fall too slowly
your player character should be like, 1-2 units
ok so you just haven't done anything regarding gravity yet
might have to disable automatic asset refresh and refresh manually
the colision box is like, 2x2
not really, just changing it in the UI
yeah that's fine then. the issue is that you're still resetting vertical velocity
how do I refresh manually?
how exacly?
ctrl+r, not sure it works if automatic asset refresh is enabled though
you're assigning to velocity/velocityY still. if you want it to fall according to gravity, you need to not change Y at all
Ah that, yea that did, just seems a bit potato potato make the character fall with very high gravity value or assing Y velocity
it seems like you just haven't written code that would let gravity work normally yet
Maybe, I'll leave it like that for now and continue to follow the course I'm doing
ok but why not just fix it now
what's your current code
that supposedly doesn't assign to Y and needs high gravity
This is the only code I have, I was changing the gravity value for the player character in the Unity UI
ok so you don't need to make gravity absurdly high, you just need to change the code to not assign to Y like ive been saying
+ rb.linearVelocityX = direcaoMovimento.x * velocidadeMovimento;
- rb.linearVelocity = direcaoMovimento * velocidadeMovimento;
- rb.linearVelocityY = -velocidadeMovimento;
```just that change, or a little different if you changed the input to be a 1D axis
How would it be then?
it's currently set as a Vector2 there, you'd change the control type (and you might have to remake the composite since it'd be pos/neg instead of right/left)
(though as mentioned before, you'd need to consider whether you want W/S to do anything)
Eh I think it's fine this way
I don't think they will do anything
Hey, I was never able to resolve this issue. Does anyone have any ideas?
- Use logs. Or debugger + breakpoints.
- It doesn't help knowing that MoveTo runs as we have absolutely no idea as to what code it contains...
Nor what value is being passed to it.
oops, I have gotten wildly confused. MoveTo was actually the method I made. (I don't know how I forgot about that...), but I was getting it conflated with another engine I was trying out last week, which uses "MoveTo", so I thought i was calling the agents move method, but I was not haha. I've found the issue now, thanks for pointing that out lol
so im trying to set the owner of a projectile but it says type mismatch
GameObject Projectile = Resources.Load<GameObject>(GlobalManager.Constants.LightningBolt_VersionOne_Path);
Projectile.SetActive(true);
Instantiate(Projectile, handTransform.transform.position, Quaternion.identity).transform.rotation
*= Quaternion.FromToRotation(Vector3.down, this.gameObject.transform.forward);
LightningBoltScript script = Projectile.GetComponent<LightningBoltScript>();
GameObject playerModel = this.gameObject;
PlayerController controller = playerModel.GetComponentInParent<PlayerController>();
script.owner = controller.gameObject;
!code
📃 Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
📃 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.
what is the exact error you are receiving
sounds like you're trying to access it before you are setting it. what is the stack trace of that exception?
UnassignedReferenceException: The variable owner of LightningBoltScript has not been assigned.
You probably need to assign the owner variable of the LightningBoltScript script in the inspector.
UnityEngine.Object+MarshalledUnityObject.TryThrowEditorNullExceptionObject (UnityEngine.Object unityObj, System.String parameterName) (at <1e74f08236fb4c1791a523c0bf197e6c>:0)
UnityEngine.Bindings.ThrowHelper.ThrowNullReferenceException (System.Object obj) (at <1e74f08236fb4c1791a523c0bf197e6c>:0)
UnityEngine.GameObject.GetComponentFastPath (System.Type type, System.IntPtr oneFurtherThanResultValue) (at <1e74f08236fb4c1791a523c0bf197e6c>:0)
UnityEngine.GameObject.GetComponent[T] () (at <1e74f08236fb4c1791a523c0bf197e6c>:0)
LightningBoltScript.Awake () (at Assets/Prefab Scripts/Spell Scripts/LightningBoltScript.cs:17)
UnityEngine.Object:Instantiate(GameObject, Vector3, Quaternion)
AnimationListener:SpawnLightningBolt() (at Assets/AnimationListener.cs:86)
okay so it looks like it's actually happening in LightningBoltScript.Awake () which explains why this is happening. Awake is called before Instantiate even returns so whatever you are doing in Awake is happening before you assign to the owner variable. Best thing to do would be to extract what you are doing into another method that you call when you assign the owner variable
basically do this: https://unity.huh.how/references/prefabs-referencing-components#example
would start work?
i mean, sure, but the better option is still to just call a method that is doing whatever you need it to after you instantiate it
you can pass the reference to the method so owner can be set inside that method. this would allow you to make owner a property that has a private setter so that only that specific method can assign to it from outside that object
Hello, how do I fix this bug?
Ability[] is an array, perhaps you mean to call GetComponent<Ability> rather than GetComponent<Ability[]>
and yet an array is not a component
GetComponent will return one component. if you want it to return an array of components then you must use a method that returns an array
ahhh okay thank you
and keep in mind the bit between the <> is the type of component, so it will never be an array there, even for the method that returns an array
in that case how do I get an array from a different script?
this happens if I do GetComponents<Ability>
does enemyUnit and/or playerUnit have one or more Ability components? or are you trying to reference some other component that happens to have an Ability array on it?
The error is not from the get component
only one
Do you understand what line of code throws that error?
this is not an Ability component, this is a Unit component that has an Ability array. if you're trying to get the array then you need to first use GetComponent to get that component, then you can just access the abilities array from that reference
it highlights this one when i double click
since enemyUnit and playerUnit are already references to that Unit component, you just need to access the array on those properties. GetComponent is not used to access a component's variable
Coroutines are a bit like that. What's line 35?
the b1Text.text one
so apparently the set in this function causes a stack overflow
private GameObject owner;
[SerializeField] public GameObject _owner
{
get {return owner;}
set
{
_owner = value;
owner = _owner;
}
}
why have you done this?
also yes, that causes an overflow because your setter calls the setter which then calls the setter
you don't need that setter there at all. just use a method like i said
Great, then that's where the error is. Likely because you're accessing an index of an array that is smaller than the index number. That's literally what the error says.
And yeah, I recommend learning to read the errors. It tells you the exact file name and line number of the error too.
im still having trouble, idk what to do
public void SpawnLightningBolt()
{
GameObject Projectile = Resources.Load<GameObject>(GlobalManager.Constants.LightningBolt_VersionOne_Path);
Projectile.SetActive(true);
GameObject projectileInstance = Instantiate(Projectile, handTransform.transform.position, Quaternion.identity);
LightningBoltScript script = projectileInstance.GetComponent<LightningBoltScript>();
GameObject playerModel = this.gameObject;
PlayerController controller = playerModel.GetComponentInParent<PlayerController>();
Debug.Log("controller = " + controller);
script.setOwner(controller.gameObject);
}
are you still receiving the same error? or are you having trouble with some other part now?
wait I think I messed I see how to fix it. one sec
ok owner is no longer null but something else is wrong
I thought if owner was set I could get a reference to its mesh collider
but its not ignoring the collision
boltCollider = this.gameObject.GetComponent<BoxCollider>();
Debug.Log("owner = " + owner);
meshCollider = owner.GetComponent<MeshCollider>();
Physics.IgnoreCollision(boltCollider, meshCollider, true);
StartCoroutine(DestroyThis(5));
this is in start
Are you sure that both colliders are present on the objects? GetComponent does not search child objects. And owner exists?
yes I have the mesh collider on the owner and the box collider on my projectile prefab
Also are you using a trigger or just solid colliders
I know it works because I have ontriggerenter destroying the object once it collides with another
with Destroy();
Not sure if IgnoreCollision affects triggers. Likely not
oh
probably not since triggers don't collide
weird cuz I have the projectile spawning inside the player while I figure out collisions and as soon as it spawns it destroys itself
If you want to use a trigger then just check in ontriggerenter if the other object can be hit by this projectile, or use layers
well Trigger messages still happen with trigger overlaps. this is not a collision though. but if the object already has a reference to the collider it shouldn't be interacting with then a simple if statement will be enough
oh ok ill try it
also i'm curious why that code is in Start, wouldn't it make more sense to have put it inside that setOwner method?
ig so
i mean, that was the point of creating that method, no? to move the code that depends directly on setting that variable into it
Yet they respect the layer collision matrix 🤷♂️
in that case, i think it's just an oversight in naming the matrix since it does affect triggers and collisions. should have called it something like "layer collider matrix" instead
Right, thats my point - who knows if IgnoreCollision is "badly" named too, i can't test right now though
@slender nymph Just wrote a lil test script and IgnoreCollision does affect OnTriggerEnter.
@compact sundial Seems like it being a trigger is not the issue
The OnTriggerEnter was probably getting called before Start, so the ignore happens too late
Let's just accept that unity counts trigger interactions as "collisions" in a lot of its terminology and not be pedantic about it
is it possible to run a function once all of a specific type of object are done instantiating? I have a bunch of objects that need to all exist before the function is run but rn it's having a race condition because it runs before all of them are done instantiating
Actually wait I haven't used Awake
lemme try that
Hm that's not working for some reason
there are definitely alternative ways around this but its easier to see if I can do it this way
Does the function need to run per each object or just once?
per object
I need to wait until all of the objects are initialized and then call the function on all of them
Start should work here
because the start method adds the object to an array in a singleton, and then calls the function after
and the function depends on everything being in the singleton's array
I mean thats what I'm using right now and its not working
Add to array in Awake, do other stuff in Start
Start won't run before all Awakes have run
I tried that but it gives an error
Or whatever is instantiating them can also add them to thet array
What error and how are you instantiating these
NullReferenceException: Object reference not set to an instance of an object
PlayerPiece.Awake () (at Assets/Scripts/PlayerPiece.cs:46)
Right now I'm not instantiating them, I just have them on the scene for testing purposes
if I were instantiating them that would be easier to handle this
but its a lot easier to test this way
So something is null in that line in Awake, or in one of the methods you call there
Are you sure that BoardController.Instance exists at that point?
most likely setting up also in awake and this script is running first
I mean that is also defined in awake
yeah
so just access it in Start
That doesn't work though because it needs to run after all of the other objects are instantiated (the Start method of all other objects of the same type has run)
is there something like Start that runs after Start?
You could set the singleton's execution order to a lower value so its Awake always runs first
(Or make Start an IEnumerator and wait for end of frame but that feels hacky)
Could be fine though
looks like that worked! thank you
My navmesh agent path is saying its complete when it should not be what can I do about that? It seems that something is wrong because its constantly saying path complete.
it recalculates, path complete and thats a loop it goes into
PathComplete means that the path to your point has been successfully calculated, not that the agent has reached the destination
So to set a destination i use .destination then? This makes sense now that youve said it but I still dont know how come that it worked before but it does not now. So how do I push him into that direction with code?
perhaps ask in #🤖┃ai-navigation
The fuckers radius was wobly. It looks like it works now lol
Hello, i have a little question.
Whenever this part of the code is called, my gameobject stop being affected by gravity which is an issue.
I tried looking for gameobject not affected by gravity while moving unity, but i got nothing.
Can someone please help me ? Thanks !
you're setting the Y velocity to 0 there
so it stops the acceleration from gravity every frame
use the current Y velocity there instead to let gravity accumulate
Thank you ! It was obvious i guess... How can use the current Y velocity parameter please ? I tried putting owner.y but it obviously didn't worked well..
Nvm i think i founded it online with the unity's website 😅
well, that wouldn't exist. think about what fields represent the linear velocity there
you're reading it back right after in the debug log
That... Is also true... TwT
After a little fail..
✅ IT WORK ! 🥳
Thank you as always Chris 🫶
beautiful lmao
Unrelated but why do you override Update here? Do you have a base object that implements Update?
Because FYI, Unity will track the Update method. Even if disabled it's added to the queue. It's somewhat negligible, but it still adds up and this is easily avoidable by not adding an empty body everywhere (assuming it's empty). If you keep doing this with thousands of objects it can make a difference.
Better to just add the Update method where needed, just like everything else.
Hey @burnt vapor, thank for taking the time to ask me that.
I do it because we are doing a group project, and the best dev proposed me to use "State machine" and other thing that i never heard of before. So i have a enemy state manager like that.. And he told me to override the function (there was error before i did it)
Do you think it's not the great way of doing so ?
Honestly I think experience wise I can't really answer this very well. I often just comment on code syntax and general things like this.
However, it does seem kind of wasteful to call an update every frame for this. Generally games implement a tic system which updates the state of monsters. This sounds better for your use case, but I don't know what your code actually does here.
Does the code actually do anything or is it all boilerplate just in case?
I'd feel like it's better to have a main Enemy manager that tics and then calls an update on all enemies when it matters, instead of having each enemy do their own work.
Very much depends on the variance of enemy's, how different they should be have. You can have a statemachine built into a scriptable object format that work really well for animation variants and attacks, roaming ect. While calling update constantly on these enemy's might not be the greatest idea, definitly like he said use a single update to update a enemy type, you can use more updates per enemy type or multi thread it. But also depends if this is for a multiplayer game so.
You could also go as far as making a swarm system, with personality tokens, and blend between swarm state and active state to save on performance
After a bit of digging I found this blog post, which is an interesting read about this: https://unity.com/blog/engine-platform/10000-update-calls
According to the blog post, a manager like I mentioned might even improve performance by itself apart from being easier to use.
Yea calling many functions only in c# yourself is more performant.
There is extra cost when going from native to managed (such as when unity invokes Update)
Yea but some cases may then benefit from using entities but that is hard to just convert everything to later
Alright guys, i'll go and talk with him in order to code better ! Thank for taking your time in giving observations and advices ! 😆
By the way, i need help with RayCast now..
So basically, i want to prevent my AI's to fall of ledges.
So ive writted this :
{
Debug.Log("An empty floor as been detected !");
}```
*(note that ive put the "Walls" layer to my... Floor. Because why not)*
Yet the Debug.Log is always printed !! Do someone knows a bit about Raycats and could help me please ? :( Thank !
Do the yellow lines show the raycast? If it starts inside the collider (which might happen if the character's pivot point is at the feet) it won't detect the collider
You could try to start the raycast a bit higher (transform.position + Vector3.up * 0.1f)
Yes @keen dew it does !
I tried everything 😅 including putting the raycast wayyy above, and putting a giant floor all around... It still print :(
I'm not sure what that screenshot is supposed to show? Those lines definitely look like they're completely inside the floor
Exactly ! Yet Unity send the ""An empty floor as been detected !""
Yes but if the raycast starts inside the collider it won't detect it
If the lines are completely inside the floor then it's expected that they won't detect it
Explain your situation a bit better, i can definitly help
Oh, alright, thank you !
So, i want to make a RayCast that will check if there's a floor below the AI, if yes, print :
Debug.Log("No empty floor detected !");
if no :Debug.Log("An empty floor as been detected !");
So here's the code that manage the detection ;
Here's the line that call the function :
owner.Roots.GetComponent<RayCastLedge>().CheckForFall(3f, owner.layersToCollideWith);
And here's the entire code of my Enemy. it is a state Machine :- https://pastes.dev/HmkR4psd0v
Im actually doing a few test because all of the sudden, it kind of seems to work. Once i'll dig more and have news, i'll let you know !
Simple answer use a checksphere
Hmm never heard of that. I'll check on the web then thanks !
Though you can use a raycast a checksphere is much simpler and can be packed into isGround bool
Now if your trying to predetermine if there close to a ledge thats a different story
To predetermine that kind of thing you only really need 1 raycast in there forward direction, a offset for how close they should be able to get to the ledge, and a raycast height, for if you want them to be able to drop off a certain ledge height if it finds ground.
or use the 2d version if in 2d
you can actually use this, idk if theres a 2D version but this is what i was talking about
https://docs.unity3d.com/6000.3/Documentation/ScriptReference/Physics.CheckSphere.html
ref int nex_spawn_time = null;
GameObject[] mobs;
int max_alive;
float cd;
if (is_boss)
{
max_alive = max_amount_of_bosses_alive;
mobs = existing_bosses;
nex_spawn_time = next_boss_spawn_time;
cd = boss_spawn_cd;
}
else
{
max_alive = max_amount_of_normal_mobs_alive;
mobs = existing_normal_mobs;
nex_spawn_time = next_normal_mob_spawn_time;
cd = mob_spawn_cd;
}
nex_spawn_time += cd;
//spawning code here
I hope you get it what I try to do, to make a reference int variable, but it doesn't work like that, what am I meant to do?
I can just put is_boss check later to determine what to use but I feel like that would be less clear
doesnt really seem like your using the ref for anything though, doesnt seem to need ref
You also cant ref like that anyways as well
next_boss_spawn_time and next_normal_mob_spawn_time
are out of scope
I mean they are not within method and I want to increase their value
I dunno maybe that would make most sense to insert all those variables as method parameters
still I am curious
what if I want to make a reference variable for a non reference type
I could make a property but it feels overkill
I mean you can i guess, but you dont really have to, im still not entirely sure what your issue is though, like what is your purpose for trying to make nex_spawn_time a ref int anyways
if it won't be ref I would change the variable inside method
but I want to change variable outside of the method
if it was a reference type variable it would work out
Ah i see, you can make it a ref within the method (ref here), you cant directly do it like that
The issue is a symptom of bad code design
I suspect that
If you have variables like normal_spawn_time, boss_spawn_time etc they should be bundled into a class, then you wouldn't have any issues with references
I thought that making a class if I just have 2 types of enemies excessive
tho I am not sure I understood what you meant
Trying to get around it by changing individual int variables with references is much more excessive
No realistically you should do it properly regardless if it seems excessive
who defines what is proper
Thats a bit cheeky to say is it not
If you put the variables into a class (let's say called Enemy) then you can just do
Enemy enemy = is_boss ? boss : normal;
enemy.spawn_time += cd;
or just pass it directly to the function
pretty blunt yeah
I mean I am not sure what would be optimal and what not time spent coding wise
The best way i can say it, is if your starting to have to find hacky ways of doing something your most likely not doing it properly
Proper code is typically pretty fluid and expandable without much headache.
I am not sure if that would make sense or I don't understand what you are saying
what I am working on right now is a script which keeps spawning enemies every N seconds unless their limit in the world is reached or their number is depleted
but bosses and regular mobs had different values for that
I just went making 2 separate but identical code pieces and it worked
now I am trying to merge
Right, and the idea for merging them is to make a class that holds those values
and having two instances of the class, one for the bosses and one for the regular mobs
It could even be a ScriptableObject
Bad, make one class, The Enemy class, this class will cover everything they have in common, then create 2 classes expanding off that class which is where youll code there uniqueness, with 0 waste or duplication of code
Please do not use ref or try and turn a value type into a reference type
There's very little reason to do this. if your concern is references then there's probably an easier way than to instantiate a reference for a value type
It sounds like you just need to turn it into a class-scoped variable, or at worst make it static. But it's hard to say with the example
A ScriptableObject sounds the most reasonable, though
won't cut it but I now tried to make it a class and it looks... neat
A class containing the state?
public class EnemyGroup
{
public WeightedItems mobs_and_weights;
public int left_to_spawn;
public float spawn_cooldown;
public float nex_spawn_time;
public GameObject[] existing_ones;
}
I am not sure what state means
So basically a ScriptableObject, lol
is it?
next_spawn_time is constantly changing
That's fine, you can edit the data. It just doesn't persist when done from a script (which I'd argue is exactly what you want here)
tho all of those values would be changed inbetween different setups of the game
script can change SO it have without affecting other SOs like it?
anyone know how to add drifting to this?
I suppose it's more of a physical problem
what the friggity diggity should I use if not RigidBody
Assets\Scripts\Enemy\EnemyBase.cs(42,13): error CS0246: The type or namespace name 'RigidBody' could not be found (are you missing a using directive or an assembly reference?)
private RigidBody rb;
nvm it's Rigidbody, not RigidBody
If you correctly configured your IDE it should point this out with quick actions
What the friggity diggity indeed
This server channel is for code problems, this is more a spoonfeeding question and tbh I doubt anybody will answer it
!ide for instructions
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
• :question: Other/None
I already figured it out, look below.
I'm well aware, just pointing out that next time you can use quick actions to possibly fix the problem
Your IDE can often suggest a similar word (e.g. Rigidbody) and the necessary namespace to include if needed
it didn't show as an error in the IDE, and didn't show me quick actions
but thanks anyway
yeah so you should configure your ide so your ide can help you next time
huh I just checked what would mine do and it just replaced RigidBody with Rigidbody without telling me
I can see myself forgetting wordings
Having a configured ide would provide word suggestions/completion. You'd only have to vaguely remember the name (not spelling or upper/lower case)
okay
Is it ok for me to not memorize a code? I know how it works but i cant memorize it, I often look at my code screenshot when i code
you typically don't memorize logic, but understand it to a degree that you can replicate it
it's ok to look at what you've written before, it'll take time and practice to really internalize it
try challenging yourself to rely on it less (not necessarily banning yourself from checking though)
I understand how it works but usually I forgot how it's supposed to be written
as in, the syntax?
Yea
ah yeah that part will also take time in its own right
there will be some parts that you need to memorize, like how specific keywords are spelt or how a for is formatted
overall there will be some rules of thumb you can use though, like x() for functions and {} for groups (blocks/bodies)
meanwhile I don't remember how for and foreach work because IDE autocomplete them
well not work, look
Alright thanks for your insight
soon I ll start to feel like I am a vibecoding llm
Guys i just started learning unity to start a game I’ve made in Python but want to convert to unity. Will a lot of my programming skill transfer and how important is programming (how much will I be using built in unity features vs coding)
programming is built on several skills
many of these will carry over, like decomposing logic, problem solving, debugging, reading docs, reading errors, researching
some will not be 1:1, such as the same concepts having different names or different spellings
some will be kinda fighting you, specifically your muscle memory with python as a language
I’m not too worried about c# as a lang because I know around 6 languages pretty well so I’m used to learning some new syntax/concepts
But like how much of developing in unity is coding
Is it Almsot all of it
Is it 50/50
Or are you mostly using tools in the engine
Also thank you for the response
for loops are a foundational feature of basically every modern language so one you do want to learn and remember 🧠
what kind of tools are you imagining here?
making a game is mostly coding
this is true for any engine
Like for example, in previous games I’ve made in purely programming langauges, I would even have to code all of the physics, rendering, etc
i mean the Unity API is pretty robust and comes in with certain built in things, like physics rendering etc.
you still need coding to access these features
So you spend more time in a coding environment than the unity engine window?
not nescessarily
Well that’s kind of what i want to know, how often are you using the tools unity has in the window vs writing code elsewhere
Like let’s say you wanna put some text on the screen
that also depends
Are you doing that in the unity engine window
are you using UGUI or UI toolkit for example
Or through code
both are possible
I’m not familiar with either of these
i mentioned them as an example
that the answer to your question is really just "depends"
but you will be in editor a lot and you will be coding a lot
that is certain
making an entire ui through code sounds painful. i use the unity editor to place stuff on the ui
And as i understand you can use code to modify those objects (with what I’m used to, you have to code everything)
i just click create > text, then move it to the right place, and change settings on it to make it look good (like different font and stuff)
but if you want the text to change during gameplay, then yes that would be done through code
Yeah it’s hard to understand the example as I’m not sure what those tools are that’s all
Okay that makes sense to me
Thank you
I keep mixing up ; and , and not sure I ll ever stop
just practice some more and you will remember. ; is used most
; is used to end statements and declarations, , is used to separate stuff in groups (arrays, declarations, arguments, parameters)
yeah I mean the way for looks
for (int i = 0; i < group.existing_ones.Length; i++)
feels like there have to be ,
ah for that one, they're separate clauses
think about how , could be ambiguous within each individual clause
int i = 0, j = 0 is valid as an initializer
a < b, b < c is valid as a condition (though not particularly meaningful)
i++, j++ is valid as an increment
also in that, for is basically syntactic sugar for a while with some extra bits, they're all used in separate places
a < b, b < c out of those 3 doesnt seem to be valid
other 2... first I nevers saw being actually used but makes sense, last, why does , works instead of ; while those are two separate instructions?
i++, j++, why
there's a comma operator that evaluates each expression and evaluates to the last one
the comma operator is also used in the last one
it only really makes sense when the non-last expressions have side effects, hence why they aren't really meaningful in the condition part
something like i++, i %= 10 might be more useful
I mean 2d can't compile
as for 2 increments with comma inbetween
it seems that comma inbetween statement expressions is inique to loop declarations
I never knew
huh, apparently c# doesn't have a comma operator
other c-family/style languages do, like c/c++ and js
(which, C is where the for loop syntax is from)
reading about it it looks kinda useless in a sense u can just call left before checking right
sometimes you want things in expression positions
How can I programmatically test multiple displays in unity? I try setting the target display for a camera in code and it doesn't work. it seems to only work if I do it manually in the inspector
You should be able to use this just fine in editor
https://docs.unity3d.com/6000.4/Documentation/ScriptReference/Screen.SetResolution.html
this is the resolution, I meant using like a second monitor
unless I'm missing something
Oh I'm dumb but you should be able to open multiple game windows and select the display it uses
I don't know if this can be done via code
so if you change via code is not updating ?
according to the docs, in the editor there is always only one display
in the Display.displays list
oh thats odd. I guess you'd have to use built exe to test
not super familar with stuff like additive loading but is it known to fuck with cinemachine???
not really but we cannot answer specifically without knowing more
you might be winding up with two Cinemachine Brain components active at once (controlling two separate Cameras)
im like in scene 1 , additively load scene 2, then from scene 2 i load scene 3 & unload everything else, and once im done with scene 3, i load scene 1 and additvely load scene 2 again and i think the code works but any cinemachine gameobjects completely dissappear
im like spawning the player back into scene two and its working all except for the fact taht the camera just disappears but the main camera stays
scene 2 has no cinemachine or base camera
idek what could possibly cause this
Is it possible to instantiate a UI button at an x, y position?
I'm trying to do a turn-based RPG and currently trying to do a targeting system where, after I choose an ability, buttons appear on screen to let me choose a target
if it's a single target for enemies, the buttons appear over enemies, if it's aoe it's one big button, and if it's self-targeting the button appears on the player character
or would this be better with game objects rather than UI
which objects ? are you talking about Cinemachine camera / component?
anything is possible
yeah
correction I'm trying to instantiate a button at the location of a game object
thats the same thing
use WorldToScreen to translate positions
the game object the cinemachine component is on just completely dissappears from hierarchy
and the cinemachine brain seems no long hooked up
if its part of a scene you're unloading that kinda makes sense
i mean but im loadingit back in though?
thank you
there should be new ones but the brain wont auto adjust to new one afaik
there arent new ones though </3
sounds like maybe you've got a singleton that is destroying extra copies, but without actual context it is hard to tell
are you certain they were part of that scene in the first place ? without seeing the complete setup is hard to tell
uh yes i think?
wouldnt that leave a copy
if it's DDOL the one that survives would be in the DDOL scene. but of course you still haven't shown context so it's only a guess
nothing pops up
we need more context, like any relevant code. also the scene appears to be unsaved, are you certain that object exists in the saved version?
oh ok
!code
📃 Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
📃 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.
and, again, are you certain that the object that is missing is in the saved version of the scene? if you haven't saved the scene since adding it then it is not so when the scene is loaded from disk it only loads what has been saved
yes
okay, i'm only confirming this because the scene was not saved in the screenshot you provided above. but just as a precaution you should make sure you do save it just in case
there's also nothing in that code that would destroy an object (other than ones being destroyed by unloading the scene) so this may not be all of the relevant code. does that Cam object have any other components besides the CInemachineCamera one?
uhh yes but its just for perlin noise though it is a singleton
well i did already point out that the issue could be caused by it being a singleton, but that entirely depends on the implementation so show it
i'm guessing that is 100% the case though, especially since the scene is being loaded additively, the new one destroys itself before the old scene is unloaded
i dont think this would have caused any issues? idek
yep, that's it. it's not DDOL so the old one doesn't stick around
there isnt any cameras in the additive scene though so shouldnt this be the only camera
that is persistent
but there is! this scene you are having issues with is being loaded additively, is it not?
uhhh when i load it normally additively the camera works fine, but when i try and load it from another scene i load the base scene and then this scene additively the camera breaks
right because when you "load it normally additively" there isn't already an instance of that singleton, right?
so when you load it additively again and there is an instance of that singleton, the new instance destroys itself because an instance already exists, but then you destroy that existing instance by unloading the scene that it exists in (since it isn't DDOL), but you only unload the scene after the new instance has already been queued for destruction (since that happens in the first frame the scene is loaded, the same frame you queue the new scene to be unloaded)
am I not able to use SetActive for buttons?
ah ok
SetActive is a method on the GameObject class, if enemyTargeting[i] is a component you need to either get its gameObject property or use the enabled property (if the component is disabled not the gameobject)
basically what happens is you load the scene additively, the singleton spiderman memes then kills itself, then the old singleton is also killed
Hey folks, don't know if this is the correct channel or not, but I have been running into trouble with tilemap colliders and rigidbodies, specifically with my player'r rigidbody clipping. I've already tried:
- Kinematic -> Dynamic on the player
- Discrete -> Continuous detection on both player and tilemap rigidbodies
- Changing the player collider's size and type
- None are triggers
I use Rigidbody2D.MovePosition in my PlayerController script. Is there a good fix to this?
buttons are components, so they don't have an active/inactive state - the checkbox you might see on components is enabled/disabled instead
ah ur right ive fixed it
are either of the colliders set as trigger colliders?
i didnt test it without the script enabled
nope
next question, if I wanted to set every object in an array to SetActive(false), do I have to use for loops or is there a faster way?
or an easier to read way rather
you do have to use a loop, but you can abstract that into its own method
hello everyone , is it a good idea to use myInstance.GetComponent<scriptname>().myvariable= variable; to change a variable value from another script , or are there better way ? ty
Choose the best way to reference other variables.
probably a UnityEvent driven approach but it depends
then you'd have to show relevant code. but if it's not a code issue then #⚛️┃physics would be the better place to ask this (providing relevant set up/context)
alrighty thank you
myInstance
is this from Instantiate? if so, you should have it typed as the component you care about to begin with, rather than GameObject or Transform
is there a way to shorten this into one method?
I don't know if it's a code issue. I'll switch to the other channel if it isn't
receive the target as a parameter?
or even just the index
wouldn't work to cover the last case
ah shit yeah, didn't notice that one
the problem is that all of these have to be assigned to a different button
was gonna say that at first too lol
ah ok, you could have 2 methods (one for players, one for enemies) and pass the index in the unityevent, for example
though typically, hardcoded indices like this could indicate a code smell, so you might want to consider doing this more programmatically
since, say, the button for targeting 3 different enemies will all be using the same method, how do I make sure it won't all just target the same enemy regardless where I click?
pass the index in the unityevent
like on the text box here?
yes, but with the right method selected
that method also does need to accept an int parameter
yeah my thing's still got compiler errors so the right method isnt showing yet but i got the idea, thank you
I think this is the relevant code:
using ...
public class PlayerController : MonoBehaviour
{
public InputActionAsset actionAsset;
public float speed = 1.0f;
public float jumpforce = 1.0f;
public float speedInAir = 0.5f;
private Rigidbody2D rigidBody;
private InputAction moveAction;
private InputAction jumpAction;
private Collider2D groundCollider;
private new Camera camera;
private bool isJumping = false;
// Start is called once before the first execution of Update after the MonoBehaviour is ...
// Update is called once per frame
void Update()
{
var newPosition = transform.position;
var value = moveAction.ReadValue<Vector2>();
var actualSpeed = isJumping ? speedInAir : speed;
var deltaDistance = value.x * actualSpeed * Time.deltaTime;
newPosition.x += deltaDistance;
transform.position = newPosition;
// ...
}
private void LateUpdate()
{
var newCameraPosition = transform.position;
newCameraPosition.z = camera.transform.position.z;
camera.transform.position = newCameraPosition;
}
private void FixedUpdate()
{
if (jumpAction.IsPressed() && groundCollider != null)
{
rigidBody.AddForceY(jumpforce, ForceMode2D.Impulse);
isJumping = true;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
var dot = Vector2.Dot(collision.contacts[0].normal, Vector2.up);
if (Mathf.Approximately(dot, 1.0f))
{
groundCollider = collision.collider;
isJumping = false;
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (groundCollider == collision.collider)
{
groundCollider = null;
}
}
}
transform.position = newPosition;
this does not respect collisions
didn't you say you were using MovePosition?
kinematic RBs don't respect collision
MovePosition is intended for kinematic RBs, so they won't have proper collision when used with dynamic RBs
AddForceY wouldn't work on a kinematic either lol
yes, Player's dynamic
okay so this now causes a few weird things:
- player doesn't seem affected by gravity as much (can be remedied by increasing gravity scale or mass)
- player no longer jumps, presumably because no surface is detected below
share the current code, in a bin site preferably so you don't have to remove parts
again MovePosition is intended for kinematics, you shouldn't use it for dynamics
you're now mixing MovePosition which moves to a specific position (and should also ideally be put into FixedUpdate) with AddForce, this combination is why gravity isn't working correctly. you need to either move entirely with forces, set the velocity, or entirely with MovePosition
should I switch to kinematic for the Player?
oh yeah, def not
should the player ignore collisions?
also yeah, ideally you wouldn't be using MovePosition with a dynamic body
in this case, no
okay, I don't know what\s happening, but now the player stays stuck in the air for a while before descending
same code? or have you changed it? because if it is the same, then the reason i just provided is why
I switched tranform position changes to rigidbody based ones
i know . . . i was referring to that code
there's also all around weirdness to the movement, so I'm probably going to need to dissect all that
so what's the current code?
// Update is called once per frame
void Update()
{
var newPosition = transform.position;
var value = moveAction.ReadValue<Vector2>();
var deltaDistance = value.x * speed * Time.deltaTime;
newPosition.x += isJumping ? 0f : deltaDistance;
transform.position = newPosition;
var newScale = transform.localScale;
if (Mathf.Approximately(value.x, 0.0f)) { }
else if (value.x > 0.0f)
{
newScale.x = Mathf.Abs(newScale.x);
}
else if (value.x < 0.0f)
{
newScale.x = -Mathf.Abs(newScale.x);
}
else { Debug.LogError("Unexpected value.x: " + value.x); }
transform.localScale = newScale;
}
only changes to Update so far
you're back to moving via the transform?
yes, the alternative was no movement
I'll have to deal with the tilemap differently
so now you don't get collisions and (though probably unnoticable at this scale) worse performance!
hooray!
collisions?
i'm confused by this question considering your initial issue was that you weren't colliding properly
I guess one of the problems I now see is with the iar control code, which obviously is badly hacked together. The easiest way to fix it is to prevent air control until things are sorted.
it's an all around mess
so start by addressing the most obvious bit, which is the fact that you are moving via the transform
oh, right the no clipping is still there
a thing to note is I never had this issue on plain sprites and box colliders
should I rely on tilemaps for side scrollers at all?
why do you keep getting hung up on the fact that you're using a tilemap. the issue is that you are moving via the transform as has been pointed out several times now
that literally ignores collision
and the only reason it kind of works is because the dynamic rigidbody is depenetrating you every 0.2 seconds
the viable choices for moving a dynamic rigidbody are setting the velocity or applying forces
this is not one of them
I switched to rigidbody.MovePosition and it was more borked than what i have
gravity straight up didn't work
for reasons that were already pointed out
do you just not pay attention to the information provided to you or what
I mean, kinda. I haven't dinner in hours.
Could you please point me to why the gravity thing doesn't work with rigidbody mode turned on? I'll probably come back later.
MovePosition which moves to a specific position
specific position includes on the Y axis
You're overriding it
you tell it to go to one place but expect it to go somewhere else. but it will do exactly what you told it to do
maybe I should zero out the Y axis position...
or maybe use one of the viable choices for moving a dynamic rigidbody
I know that having dynamic turned on should enable gravity
yes, gravity is enabled on a dynamic body. but you're still overriding it by telling it specifically where on the Y axis you want it to go
I see, changing the position directly may be bad.
at this point i'm done attempting to help, you clearly don't really intend to pay attention and just want to do your own thing so good luck
correct, that's how I make jumping work, by imparting an impulse on the Y axis
that part is irrelevant because it's not where you tell the rigidbody specifically where on the Y axis you want it to go
I understand helping people out is a thankless job. I don't mind it, I'm happy you were around.
Hey, I went back and read everything you said. I made it all work, collisions and all!
Changelog:
- Use
linearVelocityXto move the player (do I need to accoutn for the delta time?)
private void FixedUpdate()
{
var value = moveAction.ReadValue<Vector2>();
rigidBody.linearVelocityX = value.x * speed;
if (jumpAction.IsPressed() && groundCollider)
{
rigidBody.AddForceY(jumpforce, ForceMode2D.Impulse);
}
}
- Tilemap is
static, player isdynamic. Composite Collider is applied inMergemode.
only con is that the player is very bouncy haha
you were absolutely right, so I had to make sure any movement on the Y axis is only based on acceleration/force and not teleporting the rigidbody around
as in, when you collide? you can tune that with physics materials
https://paste.myst.rs/ju6o08i7
i'm having a problem where it seems that it just runs the interact method and then the escape method all in one go
the interact button is also e, but i dont really know what to do because i'd have reasoned requiring a bool to also run, and not just the input of the e key, would prevent this
a powerful website for storing and sharing text and code snippets. completely free and open source.
notably the other puzzle i made based on this system doesnt have this error, but i can only assume thats because it just hasnt shown its face yet, since before this script didnt have this problem at all
it didnt appear until i closed down the project and reopened it iirc
Well i cant see what calls InteractMethod() so can you break down or share the specific code that you think has a logic error?
i'd have thought that it returning it on the frame it was pressed would only trigger it on the frame it was pressed 🗿
Input.GetKeyDown does only return true if the key was pressed this frame
da interact script
https://paste.myst.rs/dj73s12p
a powerful website for storing and sharing text and code snippets. completely free and open source.
my glorious script which isnt exploded yet
until now
it might be ass idk
it works enough and thats goo
i did put debug logs in the original balancer script and it did run through both the escape and interact method
i changed the key to escape to be r at one point, and that completely solved it, so i can only guess that the problem is that they share a keybind
but i feel like im still doing something wrong it shouldnt be that difficult...
This will only execute interactFunction.InteractMethod(); or interactFunction.InteractMethodDenial(); on the frame E is pressed down so i presume there is something else else that does something you dont want
Its a but cruddy but I managed to parse it
it wont call itself so either add a Debug log or use a debugger to find the caller.
Your IDE can show references to a function incase you forgot
Your ide wont show UnityEvent subscriptions however, those are kinda magic
i guess i have to find what could be lurking and calling the balancer script
so the code itself isnt hte problem then?
I dont actually know the method name that you think is being called incorrectly
i just guessed based on your description
If you can plz state the exact name
i dont entirely understand
whats happening is that as soon as the interact method in the first script gets triggered, it also activates the script to immediately take the player out of it. from what ive seen it is just running through both methods one after the other.
i said before but when i changed the button for how to get out of the balancer UI, it does work again but in general it shouldnt be having this problem.
Tell me the type + method name such as MyCoolScript.MyMethod
e.g. InteractFunction.InteractMethod() is called then Poop.FuckYou() is called incorrectly!
ahhh
BalancerPad.EscapeBalancer();
i think thats whats being asked, i may possible be misunderstanding
hmmm
i will try something
if ((usingBalancer) && (Input.GetKeyDown(KeyCode.E)))
{
EscapeBalancer();
}
Well this must be what you were referring to then right?
in Update()
If this script executes its update AFTER the interact script then thats why this happens @marble hemlock
Ye
So thats it?
BalancerPad.Update() executed after BalancerPad.InteractMethod() which causes what you experience
You may need to change the execution order to make the interaction script run after this
or do its logic in LateUpdate() instead
Hmmm
Time to intentionally use late update for the first time
I shall see!
late update didnt work....
nothing works idk what t do
does anyone have any solutions for when creating a toggle that uses the same input key activates them both at the same frame one after the other?
guys i need help with animator
If you want to essentially "block" an input when you use it for that frame, we use this in our game, works great. https://nombin.dev/1kjwd100p5x1b1t4xar3d5kw
A website to host temporary code snippets.
tryna create a character controller and im doing fine but sneaking substate machine has defeated me i think
any recommendation for a library to serialize list<> to json file?
Literally any, including json utility
JasonUTIL or Newtonsoft
the latter gives you some options with Dictionary, props and more complex shit but for basic stuff jsonutil is fine
The only caveat with json utility is that the list can't be the root object, it has to be inside a class or struct that you are serializing
Show your actual code
xd was using an auto generated property and of course that is not serialized because the field is private
durr
Did you do this correctly? Is the interaction check using Late Update?
The other solution is to enforce a time delay between activation and deactivation which would prevent both happening in a single frame
im trying tyo understand input action but i dont think i do...
that doesnt help when your logic is flawed allowing state to change and immediately change back
ive said what to do so give it a try or not 🤷♂️
i did try both
putting a delay between them was one of my first attempts, but it did little beyond temporarily allowing me to see for a second that it was opening
i also did try using late update for the escape balancer, to try to separate it, but it didnt mean much
no change notably
haven't been following the original discussion, but if you're referring to unity serialization then you can mark the auto-generated field to be serialized with [field: SerializeField]
i have this script that inherits from Button, but any extra fields i add seem to not be added to the component inspector. how do i fix this
are they serialized? you might need custominspector script
or just make your own buttons?
i don't get why this wouldnt be working because i feel like it not working is a sign that any other minigame ive made or begun working on is subject to imploding
i serialisefielded them yeah
i want to use the button api
does it need to inherit from button?
would composition just be easier to deal with here
yea its too painful to ever extend UGUI components unless you really need too (e.g. scroll rect)
you have to define an inspector to add the fields or override it fully back to default
might just do this then
fortunately, you can easily look at the custom editors for the UGUI components
but composition is a better idea for this kind of thing
yeah id just rather do this honestly lol
btw composition in this context means like
multiple scripts right
so like a script for the button and a script for the values
separated but work together
been a while since i've brushed up on my OOP definitions
Your settings button uses Button for that functionality and does the rest (e.g. connect to some value or hold extra data)
yep!
i think i fixed it this is insane
huzzah
i just shut down the entire interact script for the duration of the things being open
ah yes, ofc it works for one script but not the other
i fixed it and now the crosshair stops working i'm genuinely baffled on what's going on
this happened before and i kind of just dismissed it but now i dont know..
i restarted unity and the bug reappeared i feel like im losing my mind
fortunately it only happens on the first click so thats an improvement
How would i get something to only happen after opening my game? Like if i hit the start button, i want an opening scene to load. However, if i go back to the main menu from the hub world, I want the start button to load the hub world rather than the opening scene.
Could you explain your issue again, theres a lot of chat logs to read
Just use a bool, then put that bool in a save, like openingSceneComplete, if its true then do this instead
State persistence between scene loads🤷♂️
There are many ways to do it. Look it up.
He came to unity help for that reason no, this is kinda like useless
This is enough to find the right answer. I can't list all the possible solutions here
It would also depend widely on the context of their project
Its a simple solution though, just use a bool you save that checks wether if the opening scene has been played
"just use a bool" is not a solution, as it would get reset between scene load normally.
SAVE
a bit of a non answer dont you think?
"oh to do the thing you want to do just do the thing you want to do!"
use player prefs to save the bool, or a json based save system
Save to disk? What if they want the opening scene to play every time they launch the game?
doesnt matter, but using a bool to check wether if the opening scene has been already played isnt crazy
Oh okay. So I think i get it. Trying to think of how to do the opening scene complete method.
it does not make sense to persist this, since it needs to be reset every time the game launches
This wasnt specified if they said that then i would use a different solution, your pulling hairs and making up a situation that was never clerified
if they do want this to happen only once, then persisting that flag would be reasonable
Maybe like have a first start set to false first then set it to true when the start button is selected. Then if first start is true the button will load smth else? Would that stay across scenes?
It did sound like what they were asking. Anyways, you see how you needed to elaborate several things and also your solution is making a lot of assumptions? What I suggested, would lead them to many solutions they can choose from that best suits their needs.
And also learn something in the process.
You can still use a bool though that persist through the games period cross scenes, Its called using DontDestroyOnLoad on a specific object that holds temporary information
Itd actually prob reset back to false everytime i open it tho
Indeed. You now listed 2 of the possible ways to persist state.
Ah alright. I was trying to avoid using dont destroy on load. Id have to make a whole new script for my start button. Rn the code for it is in a main menu manager that has all the menu button logic
Lookup all the ways to persist state between scenes and chose whatever suits you best.
I'll look some up thx. At least now i have a vague idea of what to do
I’m building a Minecraft-style voxel renderer where chunk meshes are procedurally generated, textured from a single atlas, and rendered with custom atlas shaders for terrain blocks plus special objects like doors, leaves, glass panes, and poppies.
Fully opaque rendering works when alpha/undefined atlas pixels are forced to black, but when I enable alpha cutout for those transparent pixels, the opaque parts of those objects start showing terrain/shadow/silhouette artifacts from objects behind them.
It looks like a depth/shadow/render-queue or shader-pass issue where background geometry is leaking through or being projected onto cutout objects even outside the transparent holes.
I have attached three images.
One image shows the leaf block, glass pane block, and poppy block, and you can see on the objects where I attempted to "cut out" the transparent parts, it just ends up not working that well.
Second image shows the door, where you can see weird artifact shadows when there are other blocks behind the door, but the third image shows that when there are no blocks behind the door, there are no artifacts.
I am not too experienced when it comes to rendering and specific cutouts or texturing/shadows etc, so any help would be greatly appreciated.
Also for each image, left side is cut out version and right side is plain black no cutout. I have also attached my texture atlas.
Been trying to fix this issue for hours upon hours and it is not working. Thanks for any help you guys have to offer!
If you need any more info in order to help, I can easily provide it
i think this should go into #1390346776804069396 not really a code question...
Could you possibly show me your shader setup
Sorry man. I hardly ask for questions, last one was months ago. I've had a really long day of just banging my head against the wall on this error and I just don't really know what to do
Did you make sure to set your atlas filter mode to point
Can you give me a quick summary of what that does
Wait
Just did a google search
Maybe that might be the issue, I'll take a look
I doubt it though, because it is only when I enable shadows?
Yeah nvm I already enabled Point
also you shouldnt have generate mip maps on either
Like you can use it but like it does not work well for that at all
You also shouldnt have compression on if you do or atleast only have it at its minimum setting
Im currently looking through your shader code i just figured i should bring those up before hand
Ah you realize that your cutout version of your shader leaves behind before rendered artifacts, your cutout shader isnt complete compared to your other one, hold on
Yeah just let me know what you mean in more detail, take your time
Yup yup
Uh @topaz gorge unfortunately it didn't work.
I did want to tell you something specific tho, that at least for the door, I can see the shadows/dark spots of the blocks that are actually behind the door. Idk if that helps. It's definetely an issue with shadows because I turned the shadows off for these objects, and there was no glitchiness like this
Kinda knarly lookin XD
Yeah I've been using Unity for quite some time now and this is beyond anything I've ever seen, I've tried so many things..
Try making the cutouts shaders forward pass fully match the opaque shader for shadow, this should realistically fix it
Okay
#include "UnityCG.cginc"
#include "Lighting.cginc"
#include "AutoLight.cginc" // <-- important
struct v2f
{
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
float2 atlasData : TEXCOORD1;
float3 worldNormal : TEXCOORD2;
UNITY_SHADOW_COORDS(3) // <-- add this
};
In the Vert()
UNITY_TRANSFER_SHADOW(o, v.uv); // <-- add this
In the fragment
float shadow = SHADOW_ATTENUATION(i);
float3 directional = _LightColor0.rgb * directLight * shadow; // <-- multiply by shadow
Should be all you really have to do
K thx
Unfortunately I did that and it still doesn't work..
Man this is confusing
(terrible image but you can see the artifacts on the poppies)
This stuff is always hard to diagnose
Let me know whatever you need to know
I can try to provide any info
I really appreciate all of your help by the way
Yeah can you give me a up close picture of everything having a artifact issue
cause it might even go beyond just shadow
Yes
i added you rq so we can talk there
Okay
I'd start from looking at the frame debugger to understand where the issue originates first. And if needed use a shader debugger like PIX to investigate the faulty drawcall.
Anyways,it should be in #1390346776804069396
We actually ended up fixing it, they just had to update there unity version, i ended up testing it on Unity 6 and it just worked im like neat
i feel like i'm losing my mind with this coding issue...
UnityEngine.MonoBehaviour.StartCoroutine (System.Collections.IEnumerator routine) (at <6a469c5cf96a43eab23a293167261e20>:0)
General.ParticleBehavior.CollectableManager.DoRoutine (UnityEngine.Coroutine routine, System.Collections.IEnumerator callback) (at Assets/Scripts/General/ParticleBehavior/CollectableManager.cs:47)
General.ParticleBehavior.CollectableManager.Collect (UnityEngine.Vector3 position) (at Assets/Scripts/General/ParticleBehavior/CollectableManager.cs:42)
General.CellBehavior.Cell.OnTick () (at Assets/Scripts/General/CellBehavior/Cell.cs:109)
GameManager.OnTick () (at Assets/Scripts/GameManager.cs:56)
GameManager.Update () (at Assets/Scripts/GameManager.cs:71)
what are the reasons for getting this, because i've tried everything i could find looking through google and docs and even tried chatgpt and nothing makes this error go away. and my coroutine will not execute. which also doesn't make sense becasue i have the exact same code executing a coroutine elsewhere in the project that works perfectly fine. but not this one. whyyy
!code
📃 Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
📃 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.
Showing the relevant code might be helpful...
inspector error, colors stuck at all zeroes (0,0,0,0), ignores color picker and even initialization
Probably should show code also, as diagnosing will be hard from that image
it starts here in a cell script:
GameManager.Instance.HandleCollectables(transform.position);
then in the instance it does this:
public void HandleCollectables(Vector3 position) {
collectableManager.Collect(position);
}
then in the collectablemanager it does this:
public void Collect(Vector3 position) {
var item = GetCollectableFromPool();
if(!item) {
return;
}
item.gameObject.SetActive(true);
item.Initialize(position, Vector3.zero, this);
_myRoutine = StartCoroutine(CollectCoroutine(item));
}
private Coroutine DoRoutine(Coroutine routine, IEnumerator callback) {
if(routine == null) return StartCoroutine(callback);
StopCoroutine(routine);
routine = null;
return StartCoroutine(callback);
}
The return type of a coroutine method needs to be IEnumerator iirc.
this is the Coroutine:
private IEnumerator CollectCoroutine(Collectable item) {
transform.position = item._startPosition;
var currentPosition = item._startPosition;
var elapsedTime = 0f;
while(elapsedTime < collectDuration) {
elapsedTime += Time.deltaTime;
if(elapsedTime >= collectDuration) {
elapsedTime = collectDuration;
}
transform.position = Vector3.Lerp(item._startPosition, item._endPosition, elapsedTime / collectDuration);
if(!(elapsedTime >= collectDuration)) continue;
ReturnCollectableToPool(item);
break;
}
return null;
}```
it is type IEnumerator
Just so you can read more about it
Log the params that you pass into DoRoutine.
The crash is caused by passing null as the IEnumerator to StartCoroutine inside DoRoutine
if(routine == null) return StartCoroutine(callback); callback can be null here
No yield return Your coroutine runs completely synchronously in a single frame. The while loop finishes instantly regardless of collectDuration
Yocan also add a try catch and a breakpoint in the catch block. Then view in the debugger to see more.
Also, I don't see where DoRoutine is being called or referenced.
yeah im pretty sure this is a unity issue, not my code:
public PointResource[] pointResources; //everything works except i cant set color variables in inspector
public PointResource test; //everything works if its not in an array?
i took out the DoRoutine to simplify the issue so maybe i could find the issue
It's in the error stack trace though..?
So either you shared older stack trace or it's still being called
Try a list see if that gets you a different result
Are you using a custom editor/property drawer/ui perhaps? Or some asset that modifies the inspector in any way?
What is PointResource
Sharing PointResource code might also be helpful.
so i added the yield into the Coroutine and i added the DoRoutine method back and now i'm getting this error:
NullReferenceException: Object reference not set to an instance of an object
GameManager.HandleCollectables (UnityEngine.Vector3 position) (at Assets/Scripts/GameManager.cs:85)
General.CellBehavior.Cell.OnTick () (at Assets/Scripts/General/CellBehavior/Cell.cs:109)
GameManager.OnTick () (at Assets/Scripts/GameManager.cs:56)
GameManager.Update () (at Assets/Scripts/GameManager.cs:71)
Well, that's self explanatory. Something in HansleCollectables is trying to access a null reference.
looks like its null in your CollectableManager, you will have to share that code
Im dense
GameManager
Fucking hell
i shared it. it was the first thing i posted which was this:
GameManager.Instance.HandleCollectables(transform.position);```
Then instance or transform is being null.
(Probably instance)
The instance is null
how?? i'm thinking it's the instance, but idk how thats possible becasue it works in every other corner of my project
When is Instance set
When you set a instance should always be done in awake, anything to do with storing instances should be done in start() or anything after awake
awake
Not necessarily, setting in the getter is also good
when is this all running
Well yes a getter is fine, but what i mean is if you reference a instance from any where the execution needs to be after awake
after awake. after start
Log both to know for sure.
Show your instance logic real quick
#region Awake Instance
public static GameManager Instance { get; private set; }
private void Awake() {
if(Instance == null) {Instance = this;}
else {
Destroy(this.gameObject);
}
}
#endregion```
you should always return after destroy, but that isnt the problem anyways
here is the instance log:
UnityEngine.Debug:Log (object)
General.CellBehavior.Cell:OnTick () (at Assets/Scripts/General/CellBehavior/Cell.cs:109)
GameManager:OnTick () (at Assets/Scripts/GameManager.cs:56)
GameManager:Update () (at Assets/Scripts/GameManager.cs:71)
I meant both.
And make the log more verbose to not get confused.
doh yeah ive got a simple script that labels arrays because i dint like element X format
Then it's likely an issue with it.
Also, the log should be in the same method that throws the error...
trying to have one script call a function from another script, so I serialized the script I'm calling the function from and used the function, but I got an error saying the object reference is not set to an instance of an object.
using UnityEngine;
using UnityEngine.Timeline;
public class Meteor : MonoBehaviour
{
public Rigidbody rb;
[SerializeField] ScoreTracker scoreTracker;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
rb.linearVelocity = new Vector3(0, -3, 0);
}
private void OnCollisionEnter(Collision collision)
{
scoreTracker.addScore();
Destroy(gameObject);
}
}
sorry i should have put it in a .txt
Did you drag the rb into the inspector to assign it
let me see if that works, i have my doubts because of separate incident
just realized that won't work because the rb is spawned in. It's a prefab that gets spawned
i logged both. and they are both not null.
if its a prefab the use GetComponent, if that script is apart of that prefab
alright
use it in start
Can you share the logs? Such that the error is visible after them too.
Take a screenshot
how do you want me to log them specificly. like this?
Debug.Log("GamemanagerInstance: " + GameManager.instance) as an example.
Well i mean if it isnt null before that piece of code runs then thats a whole seperate issue, meaning either that instance gets nulled out magically, maybe by scene swapping, or by the piece of code running before awake but that can't technically happen in this case. So i would put the log along with the line of code that calls the function that is giving you the issues
hey how do you do this
the blue outline thing
Yes, this one s fine. But also log the transform too.
use "" at the top and "" at the bottom
thank you/
it didnt show
hold on
use three of these `` at the top and three at the bottom
you can also just use ` at the top and bottom
I did this but it turned out to have the same error
void Start()
{
GetComponent<ScoreTracker>().addScore();
}
no your grave key
oh
the one above tab
Aye
you can also add cs after the first pair for highlighting like this
Well where is the component stored at, is it in the same location as the script or on a child object
it's a NullReferenceInspection
the script is stored where all scripts are, but the prefab is stored in the prefabs folder
No no, i mean the RIgidbody your trying to reference
well the rigidbody is instantiated into the scene so its nowhere until it is spawned
And when does that happen
three seconds after the game starts
the code for the score addition is in the prefab for the meteor
ok so in the same code that you instantiated the rigidbody with, after that instantiation you then assign it right, cause you can't assign it sooner
here's the full pseudocode:
-The floor instantiates a new meteor every 3 seconds
-Meteor (should) call the addScore function from the ScoreTracker script canvas and then destroy itself (second part works) when it collides with an object
ohh
Did it click
Well if your instantiating a bunch of meteors, the proper logic would be that when a metor collides then it talks to your score counter, says hey i collided right.
yeah
so I could either figure out how to make the meteors do it or just have the floor do it. That's well and good, but I think the best learning experience is to have the meteors-- the instantiated objects-- do the signalling
So floor makes meteors, the collision logic is in the meteors, you have your score class make it a Instance/Singleton, when meteor collides it can reference that instance and the function to increase your score
Nothing needs to know about the rigidbody's but the meteors themselves
hold on i'll be back
okay it wasn't exactly specified which object should be the singleton, and i'm having a hard time understanding it. sorry, this is my first game and I'm starting very basic
Your score tracker
No your all good thats what this place is for
from the video i watched, a singleton can be made by making something static. so I should make the score tracker class static?
Use an Awake method instead of Start when assigning components. Awake is for initialization, Start is when you start the actual behavior
No, you can make a static instance of it other things can communicate with
The error you have is because ScoreTracker is null. You should assign the result of GetComponent to a variable, and log it. It will say it's null.
i originally wanted to call the function when the object collides with the floor
Is this true though, cause if you setup something to create components on awake on objects, then the other awake trying to reference them will most likely have a execution order issue
Making the actual class static is something different. A singleton pattern keeps the class instanced, but instead provides a static "Instance" variable representing the only instance the class has. It's different from making the whole class static.
This documentation is very useful: https://unity.huh.how/references/singletons
You can still assign it in awake then. Awake is the first lifecycle method Unity will call on components: https://docs.unity3d.com/6000.3/Documentation/Manual/execution-order.html
A Start method makes no difference for this. You need to make sure you don't get these issues. For example, by lazily loading references or using getter properties that fetch it when needed.
You don't need to keep a component reference in another component's memory. You can just call GetComponent the moment you need it. Only when you work with code that must fetch a reference often is when you need to start wondering if maybe you should keep a reference.
Regardless you should keep initialization of data and references to Awake/OnEnable and put actual behavior from Start and methods that come after
Calling GetComponent is way more expensive than just caching a reference, i mean GetComponent is already used enough as is in a lot of other places especially in a large scale
It's not "expensive". These are negligible calls when you do them a hundred times a second. Like I said, as soon as you start working with more intensive code you need to start wondering if it makes sense to maintain a reference.
You can get away with a lot of things performance wise, you just need to wonder if it makes sense to keep a reference or if it's simpler for you to get it only when you need it. It also depends a lot on the availability of the component(s)
A bigger offender would be getting a component directly versus using something like the Find methods for components. The find methods for example make a significant performance impact if you use them, especially if you do it often.
But teaching a proper way instead of letting people do lazy things is just better in general. What your basically saying is, everytime im thirsty i walk to the fridge grab a drink and walk back, instead of keeping the water with me yk
Usually I just grab a single can each instead of grabbing the whole tray 😄
Little tung and cheek but i respect it
okay well GetComponent on awake didn't work either. I'll send the code
using UnityEngine;
using UnityEngine.Timeline;
public class Meteor : MonoBehaviour
{
public Rigidbody rb;
private ScoreTracker scoreTracker;
// Start is called once before the first execution of Update after the MonoBehaviour is created
private void Awake()
{
scoreTracker = GetComponent<ScoreTracker>();
}
// Update is called once per frame
void Update()
{
rb.linearVelocity = new Vector3(0, -3, 0);
}
private void OnCollisionEnter(Collision collision)
{
scoreTracker.addScore();
Destroy(gameObject);
}
}
you can use FIndObjectOfAnyType instead of get component
There's nothing wrong with lazily loading content. Especially ing ame design there are a million ways to tackle this. I'm just saying that if you suffer from exceptions because components might initialize later due to execution, there is nothing wrong with loading it later
as your score tracker probably doesnt liver on the meteor object
And this is something you should not do. Never use Find methods. I literally mentioned them a few messages above
But you said lazy is fine no
They're slow and messy. You suggested the singleton pattern before and this is a very good idea to work with here
i'm not sure how to use singletons. I watched a video but it sailed over my head
Im aware but i dont think they know what a singleton fully is i dont mind going on about it though
I would suggest learning more about them. They're one of the most useful things to learn.
Vertx made a great site to explain things like this
They are fantastic honestly, once you get them there pretty god sent
It also gets rid of needing to maintain a reference to the component. ScoreTracker just exists once in the scene, right? Then a singleton pattern is perfect as the whole single instance flow is enforced there.
This will probably add more confusion on your end, but imagine if you stored your pocket in your pocket, and when you need your pocket you can reach in your pocket for your pocket and use it.
haha i kind of get that actually
Whatever the case, using a Find method should never be required. It ends up being some implicit reference that is unclear if it even gets found, instead of just keeping direct references which you know will work
okay i made a singleton and same error. let me give you the code(s)
using UnityEngine;
using UnityEngine.UI;
public class ScoreTracker : MonoBehaviour
{
public Text scoretext;
public int score = 0;
public static ScoreTracker Instance { get; private set;}
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Awake()
{
Instance = this;
}
public void addScore()
{
score += 1;
scoretext.text = "Score: " + score.ToString();
}
}
using UnityEngine;
using UnityEngine.Timeline;
public class Meteor : MonoBehaviour
{
public Rigidbody rb;
// Start is called once before the first execution of Update after the MonoBehaviour is created
private void Awake()
{
}
// Update is called once per frame
void Update()
{
rb.linearVelocity = new Vector3(0, -3, 0);
}
private void OnCollisionEnter(Collision collision)
{
ScoreTracker scoreTracker = ScoreTracker.Instance;
scoreTracker.addScore();
Destroy(gameObject);
}
}
It would help if you shared the error(s), especially from the console
hold on
The code looks fine reading through it. That's how a singleton pattern works in basic terms
You can extend it with checks if Instance is already set for example, to better secure against accidental second instances in the scene
but it is assigned
And my suggestion to check if (scoretext == null) and to log the error properly so it's clear it can't be found
Wait hold up, MineTerra do you switch between a main menu and your game scene currently
And is your score script in your main menu scene or game scene
i don't have a main menu.
Ok was just checking, now your score script actually exist in the scene right
yeah
And like he said above, you have the text assigned correct
it's not assigned...
it also won't let me assign it though
That because your component is a TMP text
in your score script you need to change the reference
to TMPro_Text, instead of Text
error pops up in the code that TMPro_Text couldn't be found
you need to add at the top using TMPro;
screen shot it?
using UnityEngine;
using UnityEngine.UI;
using TMPro;
public class ScoreTracker : MonoBehaviour
{
public TMPro_Text scoretext;
public int score = 0;
public static ScoreTracker Instance { get; private set;}
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Awake()
{
Instance = this;
}
public void addScore()
{
score += 1;
scoretext.text = "Score: " + score.ToString();
}
}
haha it's all g
Your IDE should have corrected you on this. Did you configure it properly?
Could you screenshot it and show how it looks like currently?
IDE?
bro there aint no way your doing this in notepad++
no I'm using visual studio
i just don't know what IDE stands for
Did you install the Unity addon though the Visual Studio installer
And in your unity preferences under External tools you assigned the IDE your using>
can't believe that
It's your Visual Studio, or Visual Studio Code, or Jetbrains, whatever you're using
Can you screenshot how it looks like currently? With code included please
Aye out of that error though you got to learn what a singleton is
yeah
Yeah, okay, it's fine. I guess you didn't see it mentioning what class to use then
no it's just that I added using TMPro afterwards so it didn't get to autocorrect
anyways thatnks, I'll finish this little project tomorrow
Hello, i have a small question. I've made that little script that should play while in the editor, and i've recently added "LAND" as a parameter... But it does not appear in the editor, only while in game. Can someone help me please ?
Here's the entire code if needed : https://pastes.dev/8R7xDKwWRY
Thanks !
But it does not appear in the editor, only while in game
sounds like you're confusing editor vs edit mode.
marking something #if UNITY_EDITOR means it runs only while you're in the unity editor, ie the app that you use to make unity games - it won't run in a build. this doesn't mean it will run in edit mode, aka the mode when the game is not running in the editor (which is play mode)
to have stuff run in edit mode, you have to mark the class [ExecuteAlways], and then you can check whether you're in edit mode or play mode with Application.isRunning, i think? i don't remember the exact field name. note that since the class is marked here, this will affect all lifecycle messages, so you may have to check for playmode in other messages as well
Thanks for that big explanation ! So ive tried to translate using my knowledge (im french) and if i get this right :
marking something #if UNITY_EDITOR means it runs only while you're in the unity editor, ie the app that you use to make unity games - it won't run in a build. this doesn't mean it will run in edit mode, aka the mode when the game is not running in the editor (which is play mode)
This is what i want and this is the issue i encounter ! I want the list to update when im in the unity Editor; The app. But it does not.
So i should use [ExecuteAlways] as suggested ? Or is the issue elsewhere ?
#if UNITY_EDITOR doesn't really make it run in the editor, but more like make it not run while not in the editor
everything not marked that also runs in the editor lol
But it does not
it does, actually, you mentioned it yourself
it updates when you enter playmode, when a lot of code runs. it sounds like what you want here is for it to run in edit mode
the #if UNITY_EDITOR preprocessor means that the code block will only be compiled in the editor, and excluded from build.
Alright, i think that this is what i want yes. It's weird, i used a tutorial and everything worked fine and now that i've added a new line it break... But if the solution is to use [ExecuteAlways], i will ! Thanks for the explanation
if you want to run logic in the editor you have the following options:
- the OnValidate function, will make your code run in the editor every time an inspector value is changed
- the Reset function, will run when the script is attached or reset to the default values, useful for assigning default values (judging by your code this might be what you need)
- OnDrawGizmos/OnDrawGizmosSelected, these functions are specifically designed for drawing gizmos and handles but they do technically run logic in the editor
- [ExecuteInEditMode] [ExecuteAlways] attributes, will make all your unity event function in the class run in the editor, this might not be always ideal
- [ContextMenu] attribute, you can add this to functions to run them from the context menu of the inspector
- Custom editors, you can create custom editors to add editor only logic or debug features to your script
Oh ! You are a legend, using "OnValidate" worked and now the value do appear ! I will copy/paste your message somewhere to be able to read it if needed, thanks you, Chris and v0lt, for helping me out ! :)
Hello, guys! I have a question. I would like to create my own Custom Animation System, and play animations without the use of an Animator Controller, but only using the Animation Window and Animation component basically. I would like to have an idea on how to create this system and actually think about it. Can somebody help me with that, because I have never created my own Custom Animation System. What I have in mind is to use State Pattern + FSM for the Animation Transitions.
Wouldn't that basically be copying the animator?
Basically yes. We have a restriction on my project to not use Animator at all and to create our own State Machine basically.
Okay. Then go for it. State machines sounds like the right approach.
Just note that OnValidate runs multiple times and is very inefficient and you'll never be able to change the values manually because that would trigger OnValidate which will then overwrite any changes
either Reset or ExecuteAlways Awake seem about right
Quick question.
Do you use method implementations in the interface? I mean are they effective and are there any pitfalls? Because I've never seen anybody doing that in their projects.
What do you mean method implementations?
interface is just a contract, it says whatever class has this interface must implement these specific methods. If its an abstract class then you can have some implementation but its different
an abstract class is not a contract its a half implementation think about it like this
and abstract classes can only have abstract methods
I assume they mean default implementation. It is possible to provide default implementation for the methods but usually they don't, in OOP interfaces are meant to be the interface, not the implementation
i mean. both interfaces and abstract classes can have static members as well
Newer c# expands upon this kinda stuff too btw
CoreCLR my beloved
"Hey, can someone help me? I don't know why my NPCs can't talk to each other, and because of that, I can't continue with my quest."
code
!code
📃 Large Code Blocks
Use links to services like:
https://pastes.dev/
https://paste.yunohost.org/
https://share.sidia.net/
https://paste.ofcode.org/
https://paste.myst.rs/
📃 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.
and could you be more specific about which part is having issues?
No, I don't know why this is happening. Everyone in Unity got caught up in it, but I still can't talk to my NPCs anymore.
Sorry, my English isn't very good.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
I would suggest you start by figuring out if your code is being entered at all. Add debug logging to various parts of the code and see if the console logs them. From there we can maybe determine at what step the code stops running (or doesn't run if nothing ever gets logged).
https://unity.huh.how/debugging/logging/how-to
Specifically place it at the very start of your Start method too. That way we can determine if the code is ever entered.
If you don't see the log appearing at all, that would mean the component never runs the method. This could be because the component is disabled, for example. Alternatively you haven't placed it in the scene at all.
Oh wow, thanks for warning me, i'll note that
using System;
using System.Collections.Generic;
using UnityEngine;
namespace _tmp {
[CreateAssetMenu(fileName = "RanklistData", menuName = "Scriptable Objects/RanklistData")]
public class RanklistData : ScriptableObject {
public StringIntDictionary PlayerScores;
public List<int> TestNumbers;
}
[Serializable]
public class StringIntDictionary : ISerializationCallbackReceiver {
public Dictionary<string, int> Dictionary = new();
public List<string> Keys = new();
public List<int> Values = new();
public void OnBeforeSerialize() {
Keys.Clear();
Values.Clear();
foreach (var kvp in Dictionary) {
Keys.Add(kvp.Key);
Values.Add(kvp.Value);
}
}
public void OnAfterDeserialize() {
Dictionary = new Dictionary<string, int>();
for (var i = 0; i < Mathf.Min(Keys.Count, Values.Count); i++) {
Dictionary[Keys[i]] = Values[i];
}
}
}
}
This is more about learning I'm aware there is probably much easier/better solutions but I wnat to understand this Serializing concept.
I get the Player Scores In the Inspector and Also Keys and Values. But when I click the Plus symbol nothing happens. No error, nothing.
fyi there does exist a SerializedDictionary asset you could check out to see how it does stuff, for this learning thing
your question might be better put in #↕️┃editor-extensions though
thanks ill look into it. on the first sight it confuses me just more. I'll post in Editor Extensions if I'm lost
can i ask shader code questions here
I suspect that OnBeforeSerialize is getting called continuously when the inspector is open, or at least when the + button is clicked, and that clears the Keys and Values.
Check if that's the case, put a debug.log or something
You are absolutely right it does get infinitely called. Gonna check how to fix that thanks!
i put it in the wrong place mb twin
Hey chat, is it possible to make navmesh agent on 2d side view project
use 3D one and use orthocameras / sprites
or keeping it truly 2D you need something meant for 2D like H8Man one
I am programming in unity after a while, why is this method deprecated. What is the alternative?
it usually tells you the alternative
the why ? only unity internally knows that..
things change often, especially if for optimizations purposes etc. nature of software
it still works but in the future it may not
there is tho, expand the deprecated message or check docs
uh I think it really is obsolete now
this i a transition into the new ECS/Gameobject system they're trying to merge into
I think any object might work because I have only one of it.
Obsolete/Deprecated still work fine. Until it wont in future updates / unity versions
in this case is not a huge deal considering we're not in the ECS/GO mix system yet
I don't think I am gonna update my project to another version anyways so I think it's safe to use it
but also
Note: This function is very resource intensive. It's best practice to not use this function every frame and instead, in most cases, use the singleton pattern. Alternatively if you only need any instance of a matching object rather than the first one you can use the faster Object.FindAnyObjectByType
yeah ik that, but it's only being called once in start so that won't be an issue
I'd still use .FindAnyObjectByType since thats not deprecated anyway
yeah I used that one
it works perfectly so there is no reason to use a deprecated one
thanks for the help!
Sorry, been waiting for a while can anyone help me with my post in #1390346776804069396 ? Been trying to get it fixed for hours now. Yesterday too
dont crosspost
Hello, I'm currently learning in unity and I ran into a problem which isn't addressed below the texts. Everytime I click spacebar a banana spawns because of the prefabs, the real problem is when it goes out of bounds, it deletes the banana, but it doesn't just delete that 1 thing that went out of bounds, but as a whole, meaning I can no longer access it
how do I fix it?
you're most likely cloning the scene object instead of cloning prefab from assets
show instantiate code
dont share screenshots of code and show it as a whole so context makes sense
!code