简体   繁体   中英

Does not contain a definition for 'AddComponent' and no accessible extension method 'AddComponent' error in Unity

In the code below, I'm trying to create an instantiate game object and have the component added to the expose to Editor but coming up to an error below in Unity. It seems the _currentPiece can't be added to the ExposeToEditor and I'm trying to find a fix for it. What would be the workaround?

error CS1061: 'SnapPiece' does not contain a definition for 'AddComponent' and no accessible extension method 'AddComponent' accepting a first argument of type 'SnapPiece' could be found (are you missing a using directive or an assembly reference?)

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 }); 
            } 
       }

Different to GetComponent which is implemented by both GameObject and Component (which MonoBehaviour inherits from)

the AddComponent is only implemented by GameObject .

You need to always go through the according GameObject like

ExposeToEditor exposeToEditor = _currentPiece.gameObject.AddComponent<ExposeToEditor>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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