There are multiple possibilities to access a field of another script, here are a few:
- Make a public field in the script that needs the other script. This field should be of type “gameObject”. Make a reference in the unity scene to the searched object (drag the searched object into the inspector field of the first script). Then access the field from the script. Get the script from the object and you can access the searched field.
- Use the singleton pattern for the searched script
- Make a static class and access the field directly over the class
If you have multiple instances of the searched script (with the papers-field), then you should use the first possibility.
Else if you have only one instance of the searched script (and you know that this will not change) then I would reccomend you the second possibility.
The thirt possibility is similarly to the second case, but is not a clean possibility and should be avoided.
Code Examples
1)
This code is for the class that needs to get the value.
public GameObject targetObject;
public int GetPapers ()
{
if (targetObject != null)
{
var script = targetObject.GetComponent<YourScript>() as YourScript;
if (script != null)
{
return script.papers;
}
}
return -1;
}
The “targetObject” is a field of the accessing class. The method “GetPapers” gets you the value of the variable, it returns -1 if the targetObject is null or the script was not found.
2)
This code is for the class that contains the value.
// Singleton example
public class YourScript : MonoBehaviour
{
// the local (and only) instance
private YourScript instance;
// declare the fields as normal and access the with the instance
public int papers;
// Access the object with this readonly property
public static YourScript Instance
{
get
{
// At the first call, create a new instance
if (instance == null)
{
instance = new YourScript();
}
return instance;
}
}
// Make the constructor private so there cannot be a second instance
private YourScript()
{
// Do your initialisation here
}
}
With such a class, you can easely access all fields and methods.
Just get the value with:
var a = YourScript.Instance.papers;
The advantage of this patern is, that you can have a constructor and initialize your fields and variables (a static class cannot have a constructor).
3)
This code is for the class that contains the value.
public static class YourScript
{
public static int papers;
}
Then you can get the value with:
var a = YourScript.papers;
Note that you cannot add the script to a gameobject if you use possibility 2 and 3. They are only for the case that you need not multiple instances. If you want to add the script to a gameObject, you should use possibility 1.
If you want to contribute or correct something to this comment, then feel free to edit it.
Greetings
Chillersanim
Thankyou In Advance please help me...
– princeadj14