Question by
WinteryJungle9 · Apr 28, 2019 at 12:59 AM ·
prefabtextprefab-instancefindgameobjectwithtag
Instantiated prefab won't access text in scene
In my game I have a treasure chest which spawns random objects, these objects have a script attached to them which enables a UI text when the player is within their trigger that tells the player how to use them such as "Press 'E' to use". This works well if the object starts in the scene hierarchy but if the object instantiated is into the scene it doesn't work at all and I get this error in the console: NullReferenceException: Object not set to an instance of an object HpPickUp.OntriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/HpPickUp.cs:30). Heres the script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class HpPickUp : MonoBehaviour
{
public Text useItemUI;
// Start is called before the first frame update
void Start()
{
useItemUI = GameObject.FindGameObjectWithTag("UseUI").GetComponent<Text>();
}
// Update is called once per frame
void Update()
{
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "Player")
{
useItemUI.enabled = true;
}
}
private void OnTriggerStay(Collider other)
{
if (other.tag == "Player")
{
if (Input.GetKey(KeyCode.E) && Playerhp.hpValue <= 5)
{
Playerhp.hpValue += 1;
useItemUI.enabled = true;
Destroy(this.gameObject);
}
}
}
void OnTriggerExit(Collider other)
{
if (other.tag == "Player")
{
useItemUI.enabled = false;
}
}
}
Any help is appreciated.
Comment