Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice

Question Best way to Instantiate GameObject with member field of type GameObject?

Discussion in 'Editor & General Support' started by habahut, Nov 30, 2023.

  1. habahut


    Feb 23, 2018
    I have a set up like this

    Code (CSharp):
    1. public class Enemy : MonoBehaviour {
    2.   public Weapon weapon;
    3.    ....
    4. }
    6. public abstract class Weapon : MonoBehaviour { ... }
    8. public class ClawWeapon : Weapon { ... }
    10. public class EnemySpawner {
    11.   ...
    12.   GameObject enemy = (GameObject) GameObject.Instantiate(Resources.Load("enemy"));
    13. }
    My enemy prefab asset has a claw weapon prefab in its Weapon field in the inspector. However, when I instantiate it and place it into my scene with my EnemySpawner, the Weapon field is null. I would have expected Instantiate to fully instantiate the prefab, including sub objects, but that doesn't seem to be happening. I can Instantiate the weapon as part of `Start()` in my Enemy class, but it would be nice to be able to configure it quickly by swapping weapons in the editor and prefab for prototyping.

    Am I doing something wrong to cause the Weapon field to not be instantiated? I've read unity has weird interactions with abstract classes sometimes, maybe thats affecting this? Or is there a better way to do this?
  2. spiney199


    Feb 11, 2021
    It should be instantiated as an exact copy. Suppose double check you aren't getting some other prefab that happens to be called "enemy" (definitely needs a better name) which hasn't been set up properly. Or check that something else isn't assigning
    , potentially assigning null.

    Though any reason why you can't just directly reference these prefabs in the inspector?