- Home /
GameObject.FindWithTag not working
Hello i have a script that counts score and a script on chests that tries to access that score script on the player. There are multiple chests and they are being instantiated in the Start Function. But when i try to access the PLayer score scirpt it doesnt find it. The player is tagged with Player. What am i doing wrong?
In the start function:
SCOREMAN = GameObject.FindWithTag("Player").GetComponent<ScoreScript>();
On the player:
public class ScoreScript : MonoBehaviour
{
public Text ScoreText;
public float Score;
void Update()
{
ScoreText.text = Score.ToString("F0");
Score += 45.2f * Time.deltaTime;
}
}
Is your player Active in hierarchy? GameObject.FindWithTag() function only works on Active GameObjects.
If it didn't find the player then the GetComponent in the first line would generate a null reference exception. If this is not the case then FindWithTag is working fine and your problem lies elsewhere.
Answer by Txguug · Oct 07, 2016 at 10:33 AM
If there's only one player finding it by tag in all the objects is very inefficient, you should try to message it directly. The most obvious way by adding it to a public game object on your chests.
If that's not possible something like this might work
Set up your player so that it can receive data from other game objects
public class PlayerScript : MonoBehaviour {
public static PlayerScript current;
void Start ()
{
current = this;
}
public void GetBooty(int i)
{
//handle the booty
}
}
then on your chest you can get to send a message to that player script:
int Booty;
//...
GameManager.current.GetBooty(Booty);
Your answer
Follow this Question
Related Questions
How to hit a specific object 2 Answers
Best method to manage multiple tags 2 Answers
AI script troubles 1 Answer
Getcomponent error? 1 Answer
Better solution for GameObject.FindGameObjectsWithTag 2 Answers