- This problem has been stuck on me for many days, wasted a lot of time, and now it is finally solved, let everyone avoid this pit
Write a collision script, when the character gets the target item, display the text content
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Destroyed : MonoBehaviour
{
public static GameObject txt ; //定义txt,将文本内容所在的“gain”层赋值到txt上
void Start ()
{
txt = GameObject.Find("gain");
txt.SetActive(false);//隐藏文本
}
void Update () {
}
public void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "bs")//人物触碰到宝石,宝石消失,文本显示
{
Destroy(collision.gameObject);
txt.SetActive(true);
}
}
}
After the script is written, the console keeps reporting this error
NullReferenceException: Object reference not set to an instance of an object
Destroyed.Start () (at Assets/Destroyed.cs:12)
Then I searched a lot on Baidu, csdn, station b, etc., but it was useless, and it has not been solved.
Until three months later I posted it again and saw this
[Questions for help] Questions about SetActive [unity3d bar]_Baidu Post Bar (baidu.com)
I looked at my own and found that I happened to have this script on my canvas
After removing it, I found that it could run successfully, nb
This is also an error that I was able to solve after countless failures.
An error caused by tying an extra script on the canvas
When I first started writing this, it seemed that the script I wrote was tied to the gem, and when the gem encountered a character, it triggered the disappearance script Destroyed
But then I found that no matter how I change this, even if the script is not tied to the canvas, it will go wrong. It is probably related to the number of gems I designed. Report empty), but I have designed multiple gems, yes, I just tied 6 scripts to the gems, and now no matter how I change it, it will report empty
So I modified the script, tied it to the character, and then it became the above
I thought there was something wrong with the script written on the Internet before, because it kept reporting empty, but it turned out to be my problem.....
Finally, attach a tutorial on how to show and hide text: