Hello, I understand the concept of getting a variable value from another script but only if there is a game object to use gameObject.GetComponent<“otherScript”>(); but what if there is no game object?
This is the one that needs to be accessed:
public class PointScript : MonoBehaviour {
public int playerscore=0;
//Start()
public void OnTriggerEnter2D(Collider2D other){
if (other.tag == "Player") {
playerscore = playerscore + 1;
}
}
//Update
}
This is the one that needs to access my point script:
public class HudScript : MonoBehaviour {
private PointScript score= GetComponent<PointScript>();
float PlayerScore = score.playerscore;
//start()
//update()
}
The problem might be that I want to use the PointScript on multiple triggers.
Please reply and thanks for any help.
NB Please excuse any poor formatting, this is my first posted question.
You want to use a Static variable in your PlayerScore class so that the variable becomes a member of the Class and not of any particular Instance of the Class you may have in your scene. You can then access that variable directly from the Class. See below.
public class PointScript : MonoBehaviour {
public static int playerScore; // Static keyword makes this variable a Member of the class, not of any particular instance.
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
playerScore++; // The code that any instance can use to cause the score to be incremented, since the playerScore variable is a Static member, all instances of this class will have access to its value regardless of what instance next updates it.
}
}
Now to access it via an outside class, all you need to do is use the Class name. As such.
public class HudScript : MonoBehaviour {
private static int score; // A new Static variable to hold our score.
void Update()
{
score = PointScript.playerScore; // Update our score continuously.
}
}
I hope this answers your question. Any problems just let me know.