gpt4 book ai didi

c# - 脚本之间未保存 Unity 实例

转载 作者:太空宇宙 更新时间:2023-11-03 19:48:23 24 4
gpt4 key购买 nike

我有一个脚本 Planet.cs喜欢:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class Planet : MonoBehaviour
{
public string Name { get; set; }
}

在自定义函数中,我需要生成多个行星,因此我创建了一个新的游戏对象,添加了 Planet 组件(我的脚本),并将我的属性设置为:

        GameObject planet2 = GameObject.CreatePrimitive(PrimitiveType.Sphere);
planet2.AddComponent<Planet>();

Planet planetCompo2 = planet2.GetComponent<Planet>();
planetCompo2.Name = "Planet 2";

如果我在我的函数末尾检查,所有属性都已设置,如果我检查任何行星的属性名称就没问题。

我的问题是,在另一个脚本中,我尝试获取 Planet来自具有组件 Planet 的 GameObject,但我始终有一个空对象。

示例:this.gameObject.GetComponent<Planet>()this.GetComponent<Planet>()this 处始终为 null是带有 Planet 组件的 GameObject。

为什么我的实例没有保存?我的错误是什么?谢谢!

最佳答案

this.gameObject.GetComponent<Planet>()this.GetComponent<Planet>()都是一样的,因为他们都会尝试获得 Planet来自此游戏对象的组件 脚本附加到。

这里要看的是this .你指的是这个脚本。当您从另一个脚本执行此操作时,您正在尝试 Planet此脚本中执行 GetComponent 的组件功能。如果此脚本没有 Planet组件,你得到 null .我确信这就是正在发生的事情。

我建议命名您刚刚创建的游戏对象:

GameObject planet2 = GameObject.CreatePrimitive(PrimitiveType.Sphere);
planet2.AddComponent<Planet>();
//Name it
planet2.name = "Your Other GameObject";

现在,从另一个脚本中找到游戏对象,然后访问 Planet来自它的组件:

GameObject obj = GameObject.Find("Your Other GameObject");
//Now you can do
Planet planetCompo2 = obj.GetComponent<Planet>();

因为您已经有了变量 Name在你的Planet脚本,你都可以Planet带有 GetComponent[s] 的脚本,然后循环遍历它并检查哪个名为“Planet 2”。

Planet planetCompo2 = null;

//Get all Planet components
Planet[] tempComPlanet = GetComponents<Planet>();

//Seatch for which one has the name "Planet 2"
for (int i = 0; i < tempComPlanet.Length; i++)
{
if (tempComPlanet[i].Name == "Planet 2")
{
//Found. Store it to planetCompo2 then exit the loop
planetCompo2 = tempComPlanet[i];
break;
}
}

关于c# - 脚本之间未保存 Unity 实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42673056/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com