- Home /
Player turns not working (C#)
Can someone help please?
I am making a simple board game and what to swap players turns. But I can't get a class to read the value of a variable in another class that tells who's current turn it is.
Tile Class
using UnityEngine; using System.Collections;
public class Tile : MonoBehaviour { public GameObject BeadWhitePre;
public GameObject BeadBlackPre;
public string tileStatus;
void OnMouseDown () { GameObject beadColour;
Vector3 position = new Vector3 (transform.position.x, (transform.position.y + transform.localScale.y / 2) + (BeadWhitePre.transform.localScale.y / 2), transform.position.z);
if (tileStatus == "E")
{
if (GetComponent <Referee>().currentPlayer == "white")
{
// code
}
else
{
// code
}
}
}
Referee Class
using UnityEngine; using System.Collections;
public class Referee : MonoBehaviour
{ public string currentPlayer;
// Use this for initialization void Start () { currentPlayer = "white"; } }
I get an error each time I click on a tile in-game.
"Object reference not set to an instance of an object"
And the reason is this: GetComponent <>Referee<>().currentPlayer
But I do not know what to do.
Does the object to which the Tile script is attached have a Referee component?
No. The Tile script is attached to the prefab called TilePre. The TilePre instances make up the game board. The Referee script is attached to the camera (I am not sure if this is the right thing to do). Later on the Referee script will have all the game rules in it.
Answer by boymeetsrobot · Oct 25, 2010 at 02:07 PM
A simple way to do this would be to make a static variable on the class like this:-
public class Referee : MonoBehaviour {
public static string currentPlayer;
}
And then in your other class do this:-
public class AnotherClass : MonoBehaviour {
void ChangePlayer(){
Referee.currentPlayer = "white";
}
}
Thanks. This solved it. $$anonymous$$aking the variable static allows other classes (that are not attached to its game object) to read and change the value.
Answer by pyro · Oct 25, 2010 at 02:10 PM
You have to call GetComponent on the gameObject that has the component you are trying to get.
Since you are just calling "GetComponent" on the Tile script, it is going to check the gameObject the Tile script is attached to for the Referee script.
Since you said the Tile script doesn't have a Referee component, then that is the problem right there. It's trying to get a component that doesn't exist and is returning null.
Thank you for the explanation. Now I know when to use/not use and what the requirements are of using "GetComponent".
Your answer
Follow this Question
Related Questions
What's the difference between SendMessage and GetComponent? 3 Answers
GetComponent Keeps Returning : Null?? 2 Answers
error on script getcompnent function 1 Answer
'mesh' is not a member of UnityEngine.Component - Explicit Typecasting for Android 1 Answer
Accessing variables in another script using GetComponent() 0 Answers