Home > front end >  How to add components to GameObjects upon initialization?
How to add components to GameObjects upon initialization?

Time:09-17

I want to use this code

GameObject mapOutline = new GameObject();
LineRenderer top = mapOutline.AddComponent<LineRenderer>();
LineRenderer right = mapOutline.AddComponent<LineRenderer>();
LineRenderer bottom = mapOutline.AddComponent<LineRenderer>();
LineRenderer left = mapOutline.AddComponent<LineRenderer>();

However I cannot add these components at the same time the game object is initialised, I get the error "A field initializer cannot reference the nonstatic field, method, or property 'ChooseGameMode.mapOutline'" So is there a way to create the game object already with these components? I know how I could do this by already having the object exist from the unity editor and add the components there but I would rather create it all in code.

CodePudding user response:

As I mentioned in my comment, I believe the error you are describing occurs when you attempt to call methods that are not thread-safe within the field initializer or constructor of a class. To be more specific, the methods you are trying to call do not yet exist when you are attempting to call them. To fix this issue, simply move the method calls you are making to a function. Your code can look something like:

public class ChooseGameMode : MonoBehaviour
{
     GameObject mapOutline;
     LineRenderer top, right, bottom, left;

     private void Awake()
     {
          mapOutline = new GameObject();
          top = mapOutline.AddComponent<LineRenderer>();
          right = mapOutline.AddComponent<LineRenderer>();
          bottom = mapOutline.AddComponent<LineRenderer>();
          left = mapOutline.AddComponent<LineRenderer>();
     }
}
  • Related