1
votes

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 }); 
            } 
       }
1
you probably want _currentPiece.gameObject.AddComponent... or such, you dont add monobehaviors to monobehaviors, but to gameobjectsBugFinder
Thanks. That seems to work!Coder

1 Answers

3
votes

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