【问题标题】:ClassVar.prefab not showing in inspector in UnityClassVar.prefab 未显示在 Unity 的检查器中
【发布时间】:2021-06-22 13:30:41
【问题描述】:

我正在开发“将球射入垃圾箱”游戏。我试图获取一个预制对象(通过检查器)然后实例化它,但是当检查器没有显示输入预制游戏对象的预制选项时偶然发现了这个问题,即使这段代码:

[System.Serializable]
public class Obj
{
    public GameObject prefab;
}

应该这样做。

完整代码:

public class MouseLook : MonoBehaviour 
{
   [System.Serializable]
    public class Obj
    {
        public GameObject prefab; // Get Prefab from Inspector
    }
    
    void Update() 
    {
        if (Input.GetMouseButtonDown(0)) 
        {
            Obj obj = new Obj();

            Instantiate(obj.prefab, playerBody); // playerbody is a Transform
        }
    }
}

如果有人有解决此问题的方法,请告诉我。
这将非常有帮助:)

【问题讨论】:

    标签: c# class unity3d


    【解决方案1】:

    我很确定这不是 Full code .. 否则它甚至不会编译 ;)


    目前情况

    你定义了一个类,是的,但是我没有看到你类中的任何字段实际上使用了你的类型!

    应该是例如

    public class MouseLook : MonoBehaviour 
    {
        [System.Serializable]
        public class Obj
        {
            public GameObject prefab;
        }
    
        public Obj obj;
        // Or also
        //[SerializeField] private Obj obj;
    
        // Wherever you get this from
        Transform playerBody;
        
        void Update() 
        {
            if (Input.GetMouseButtonDown(0)) 
            {
                Instantiate(obj.prefab, playerBody);
            }
        }
    }
    

    特别注意,如果你这样做了

    Obj obj = new Obj();
    

    在这个刚刚创建的 Obj 实例中,prefab 当然不会被分配。


    我的问题是:这真的是你的Obj 类的全部吗?因为在这种情况下为什么不干脆拥有

    public class MouseLook : MonoBehaviour 
    {
        public GameObject prefab;
        // Or also
        //[SerializeField] private GameObject prefab;
    
        // Wherever you get this from
        Transform playerBody;
        
        void Update() 
        {
            if (Input.GetMouseButtonDown(0)) 
            {
                Instantiate(prefab, playerBody);
            }
        }
    }
    

    【讨论】:

    • 哦,是的,这让事情变得简单多了。谢谢@derHugo!
    • 我认为我的代码可能过于复杂 XD
    猜你喜欢
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 2020-05-26
    • 1970-01-01
    相关资源
    最近更新 更多