This is the second time i ask this.
But apparently,what i did last time is not working right now.
I always struggle to get variables from another script…
So,i have a project with like 10 scripts.
In 6 of these scripts,i have a variable,that change it’s value on a collision.
But the thing is I have one other gameObject with a script that need to take ALL OF THESE 6 SCRIPTS variables. How do i do that?
Please,do not give me a very complex answer,because im really struggling with this. Im actually good at programming/unity,but this part always gets me…
Hey friend
thank you so much for your answer,
i will only be be able to code tomorrow,sadly.
I took a look at the material you sent me
So,imagine i have a RandomVariable1 in script 1,RandomVariable2 in script 2,RandomVariable3 in script 3.
To access them,i would have to find their game objects and get their script component?
How that line of code would go,for me to simply take one of those?
Something like that?
private int StoreValue1 = GameObject.find(“object”).GetComponent();
Suppose you have an Object in the scene called “MyObject”. On it, You have a script named “MyScript” which contains the variable “MyVariable”. Let’s say it’s an Integer.
Now you want to access this “MyVariable” from another script.
First of all, You need to declare “MyVariable” as public, otherwise, you wouldn’t be able to access it from other scripts.
Your “MyScript” would look like this,
public class MyScript : Monobehaviour {
public int MyVariable;
}
Now, to access this variable from other scripts,
You can use GameObject.Find() int storevalue1 = GameObject.Find("MyObject").GetComponent<MyScript>().MyVariable;
OR you can directly assign the references in inspector, To do this, Declare a variable in the other script. public GameObject obj;
Next you can do is, int storevalue1 = obj.GetComponent<MyScript>().MyVariable;
Man,thank you so much. You helped me a lot.
I did exactly what you said,the only difference was that i used “GameObject.FindGameObjectWithTag()” instead of “GameObject.Find()”.
The GameObject.Find() didn’t work here,was returning me an error (“object reference not set to an instance of an object”). Then i changed it for GameObject.FindGameObjectWithTag() and it worked fine!
I already tested it,and it is working 100%.
Thanks again!!!
This will make it so that you can only ever reference one specific script reference ever.
What if you have multiple “Test01” scripts in the scene and you need to get a specific one of them?
GetComponent isn’t complex; it should be the default option.
Not to mention, you cannot do what you’re suggesting to do with Unity’s built-in components, like Transform, Rigidbody, BoxCollider, etc.
Making everything static is really bad practice and will only cause headaches in the long run.
Static fields should be reserved for things you only ever need one of.