Hello
I have 2 objects one of them is called Player and the other one is Sphere
Player has a script in it, that script has an int variable and its set to 1 at start
and that int variable called coin when player touches a coin that integer increases by 1
sphere object has diffrent script, I have to print coin integer from this script I tried diffrent codes none of them worked I dont know what to do right now
Well, there are several ways to get scripts or objects to communicate.
1- To get a reference to the object declare a new game object in your script GameObject myObject = new GameObject(); (you’ll have to slot the object in the inspector), then you’ll have to get a reference to the script you need to access myObject = GetComponent<MyOtherScript>(); then, you’ll be able to myObject.MyVarFromOtherScript= //something;.
2- If you are instantiating objects and you wont know the object right away or you need to get a reference to an object automatically then you have to Find the object. There are a many ways to get an object, but to name a few:
Fastest one is the tag one (you’ll have make new tag for it though, but that’s great for stuff like “Player”). The one that searches by type of script attached is only going to return the fisrt object it finds with the script, so not that usefull if you have a ton of objects with the script. You can also make the whole process I showed you in the first paragraph in a single line: myObject = GameObject.FindGameObjectWithTag("myTag").GetComponent<MyOtherScript>();
Just bear in mind that finding and object is a slow process so try to do this in Awake() or Start(), never put it on an Update(). Edit: also make sure the variables and methods to call from the other script are public. Else they wont be visible.
3- Another type of communication can be done through global variables, which can be accessed by any script. ie: make a script called GlobalVars, with a static class, then declare your variables as static too (in some cases you may want static readonly for stuff that must NOT be overwritten by other scripts), then you just access the variables using the file name + the variable name (GlobalVars.MyGvar). Static variables exist as a single entity, meaning if you change the value from one script it’ll change for all other scripts which are reading it. This is great for settings or gamestates and other data that needs to exist only once.