How to assign GameObject to a instantiated prefab via Script(C#)?
I am trying to have a popup canvas on trigger to show Level complete. My game is using instantiated prefabs for the characters. When I drop the character into the scene and pass through the trigger it works and the canvas will popup. But when I try this with the prefab, it is not finding the canvas to popup. I have tried -
LvlComplete = GameObject.FindWithTag("lvl");
LvlComplete = GameObject.Find("LVL Complete");
And neither of these seem to work. Any ideas what I can try to get the prefab to find the canvas/gameobject in the scene?
Thanks for the help!
Here is the script Im using using UnityEngine; using System.Collections; using UnityEngine.UI; using System;
public class Timer : MonoBehaviour
{
private float secondsCount;
private int minuteCount;
private Text ScoreText;
public float startTimer = 0;
public GameObject LvlComplete;
public void Awake()
{
ScoreText = FindObjectOfType<Text>();
//LvlComplete = GameObject.FindWithTag("lvl");
LvlComplete = GameObject.Find("LVL Complete");
}
void Update()
{
if (startTimer > 0)
{
SumScore.Add(Mathf.RoundToInt(Time.deltaTime * 100)); // This adds the delta time to the score as an int (in hundredths of a second)
var minutes = (SumScore.Score / 100) / 60; //Divide the guiTime by sixty to get the minutes.
var seconds = (SumScore.Score / 100) % 60; //Use the euclidean division for the seconds.
var fraction = (SumScore.Score) % 100;
//update the label value
}
else
{
}
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "Start")
{
setTimer(1);
}
if (other.tag == "Finish")
{
SumScore.SaveHighScore();
setTimer(0);
LvlComplete.SetActive(true);
}
}
void setTimer(int t)
{
Timer playerTimer = this.GetComponent<Timer>();
playerTimer.startTimer = t;
}
}
Answer by Bill9009 · May 28, 2017 at 10:39 PM
First, check the GameObjects tag itself to make sure you have spelled everything correctly.
Second, Is the GameObject you are searching for in the hierarchy or in one of your folders? (prefabs that have been instantiated are GameObjects)
Answer by xerxes78 · May 29, 2017 at 01:25 PM
Here is the canvas I am trying to trigger. Everything appears to be spelled the same and tagged correctly. ![alt text][1]
Here is the Lvl Complete with the missing game object on the prefab.
[1]: /storage/temp/94971-2.png
Thanks for your help, hoping to come up with a solution to this!
Where is the prefab located? Is it in a file inside your assets folder? Or is it a GameObject inside your hierarchy?
The prefab is in a folder in the in the assets.
The canvas of course is in the hierarchy
Alright I have searched "GameObject.FindWithTag not working" $$anonymous$$aybe this (solution will work.