不包含'AddComponent'的定义,并且Unity中没有可访问的扩展方法'AddComponent'错误

问题描述 投票:0回答:1

在下面的代码中,我试图创建一个实例化游戏对象,并将组件添加到暴露给编辑器,但是在Unity中出现以下错误。似乎_currentPiece无法添加到ExposeToEditor中,我正在尝试为此找到解决方法。解决方法是什么?

错误CS1061:'SnapPiece'不包含'AddComponent'的定义,并且找不到可以接受的扩展方法'AddComponent'接受类型为'SnapPiece'的第一个参数(您是否缺少using指令或程序集引用?)

public class SnappableSpawner : MonoBehaviour
        {
            public GameObject prefabSnapPiece;
            public float initialDistanceToSpawnAt = 1f;
            private float _currentDistanceToPositionAt;

            private SnapPiece _currentPiece;
            private int _spawnSuffix = 1;

            public void SpawnGhostToMouse()
            {
                if( _currentPiece == null )
                {
                    _snapMode = PointerSnapMode.ABSOLUTE_PROJECTION;
                    _currentDistanceToPositionAt = initialDistanceToSpawnAt;
                    _currentPiece = GameObject.Instantiate( prefabSnapPiece ).GetComponent<SnapPiece>();
                    _currentPiece.name = "Spawned-"+_spawnSuffix;
                    _spawnSuffix++;

                    ExposeToEditor exposeToEditor = _currentPiece.AddComponent<ExposeToEditor>();
                    IRTE editor = IOC.Resolve<IRTE>();
                    editor.Undo.RegisterCreatedObjects(new[] { exposeToEditor }); 
            } 
       }
c# unity3d components
1个回答
2
投票

GetComponentGameObject(MonoBehaviour继承自其)实现的GameObject不同

Component是由Component实现的only

您需要始终通过类似AddComponent的操作

AddComponent
© www.soinside.com 2019 - 2024. All rights reserved.