简体   繁体   English

Unity - 实例化对象上的GetComponent返回Null

[英]Unity - GetComponent on Instantiated Object returning Null

I am trying to access a script on another gameobject that is instantiated in my script, and no matter what I do the script always returns null. 我试图访问在我的脚本中实例化的另一个游戏对象上的脚本,无论我做什么,脚本总是返回null。

I instantiate the gameobject first by doing this. 我首先通过这样做来实例化游戏对象。

asteroid = (GameObject)Instantiate(asteroidPrefab);

after that I try acessing its script by doing this: 之后我尝试通过执行以下操作来访问其脚本:

AsteroidHandler handler = (AsteroidHandler)asteroid.GetComponent(typeof(AsteroidHandler));

To check whether or not the handler was set properly I did this: 要检查处理程序是否设置正确,我执行了以下操作:

if(handler == null){
    Debug.Log("Asteroid Handler is Null");
}else{
    Debug.Log("Asteroid Handler was setup properly");
}

The problem is this always does the null option. 问题是这总是使用null选项。 I have the AsteroidHandler script attached to the asteroidPrefab prefab, and when I Instantiate it, it Instantiates properly, as I see the asteroid on the screen. 我将AsteroidHandler脚本附加到asteroidPrefab预制件上,当我实例化它时,它正确实例化,因为我在屏幕上看到了小行星。 Still when I try accessing the AsteroidHandler script that is attatched to it, it seems to act like it isn't there; 当我尝试访问附加到它的AsteroidHandler脚本时,它似乎表现得并不存在;

I have tried a couple other methods to access AsteroidHandler but they all say its null: 我已经尝试了几个其他方法来访问AsteroidHandler,但他们都说它为null:

AsteroidHandler handler = (AsteroidHandler)asteroid.GetComponent<AsteroidHandler>();

.

AsteroidHandler handler = (AsteroidHandler)asteroid.GetComponent(typeof(AsteroidHandler)) as Asteroid Handler;

I have looked at a couple other questions similar to mine, but none of the answers seem to help. 我看了几个与我类似的问题,但没有一个答案似乎有所帮助。

Any help would be appreciated. 任何帮助,将不胜感激。

Couldn't be easier, 不可能更容易,

add this code 添加此代码

asteroid = (GameObject)Instantiate(asteroidPrefab);
// add this...
asteroid.name = "Added test item";

run the program and wait until you see the "Added test item" 运行程序,等到你看到“添加测试项目”

Check, do you ALSO see the "Asteroid Handler is Null" 检查,你还看到“小行星处理程序是否为空”

Now, literally look in your Heirarchy for the scene, and find the object named Added test item 现在,从字面上看你的Heirarchy场景,找到名为Added test item的对象

Look carefully at the Inspector, see what you see. 仔细查看检查员,看看你看到了什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM