Global Variables - Unity
So im currently making a game in unity and i wanna have a gravity tile that basically gives you velocity, depending on the tile itself - either upwards velocity or downwards velocity. I kinda did it but i cant set a different velocity for the different tiles. For example i set a velocity of 2 on the up tiles and -2 on the down tiles, but it registers the velocity as 2 and both tiles act as up tiles. I've attached pictures to hopefully clear up my problem!
17 Replies
Someone may know, but you may be better off asking in $unity
i accidentally attached 2 screenshots of the up tiles
they are very slow and often dont respond
$code
To post C# code type the following:
```cs
// code here
```
Get an example by typing
$codegif
in chat
For longer snippets, use: https://paste.mod.gg/Don't make your force static. That's causing it to share across all instances of
GravityTile
.if i remove the static will i be able to use it in other scripts?
Yes, but not the way you're likely already using it. You'll need to give those other scripts a way to get the tile you're truly concerned with if you aren't already.
The force being static is your core problem for two reasons:
- It's shared across all tiles, meaning every tile has the same force.
- It's up to Unity which force gets assigned, meaning the force could be some random force out of all the tiles you have set in your scene.
If you remove the static, then the force is respected based on how you set it in the inspector
And both problems go away.
this is how im using it but removing the static keyword does indeed break the code
As I stated, you'll need to get the active
GravityTile
component and use its instance value; something like:
You'd have to figure out how to get the current tile for your active position.
Then you can use that tile's instance data to make decisions.I need to make a custom GetCurrentTile method right?
Also should this be in Start, Update or somewhere else?
Probably update
Im sorry if im asking too many questions but im just too lost. What should the GetCurrentTile method consist of?
I recommend asking for more detailed help in the $unity server. They'll be able to provide much more information about how to properly set up your game objects and scripts to accomplish what you want without static members. I'm sure there's something out there called
GetComponent
which allows you to request a certain component in your script, but the details are outside of my realm of expertise.alright ty