Home >Backend Development >C++ >Why is `new` Returning Null When Instantiating a MonoBehaviour-Derived Class in Unity?
Resolve NullReferenceException caused by inheriting MonoBehaviour script instantiation in Unity
In Unity, when trying to create a new instance of a Rule class that inherits from MonoBehaviour, you may encounter a strange problem: even if the parameters are set correctly, the class instance returned by the new
keyword is empty.
Source of the problem:
The root cause of this problem is that the MonoBehaviour class cannot be instantiated using the new
keyword. After inheriting MonoBehaviour, the correct instantiation method is to use AddComponent()
or Instantiate()
.
Solution 1: Use AddComponent()
If you want to add a Rule script to an existing GameObject, use AddComponent()
:
<code class="language-C#">Rule rule2 = null; void Start() { rule2 = gameObject.AddComponent<Rule>(); }</code>
Solution 2: Use Instantiate() and prefabs
If you have a Rule script prefab, you can use Instantiate()
:
<code class="language-C#">public Rule rulePrefab; Rule rule2; void Start() { rule2 = Instantiate(rulePrefab) as Rule; }</code>
Solution 3: Get existing instance from attached script
If the Rule script is attached to the GameObject, its instance can be obtained directly:
<code class="language-C#">Rule rule2; void Start() { rule2 = GameObject.Find("NameObjectScriptIsAttachedTo").GetComponent<Rule>(); }</code>
Notes for non-MonoBehaviour classes:
If the Rule class does not inherit MonoBehaviour, you can use the new
keyword to create an instance and use the constructor as needed.
Summary:
When using classes that inherit from MonoBehaviour, be sure to avoid using the new
keyword to create instances. The recommended methods should be used instead: AddComponent()
, Instantiate()
or retrieving an existing instance from an attached script.
The above is the detailed content of Why is `new` Returning Null When Instantiating a MonoBehaviour-Derived Class in Unity?. For more information, please follow other related articles on the PHP Chinese website!