0

why do we have to access a component from our script using GetComponent method ? can we make its object instead?

e.g instead of

 Rigidbody rb;
 rb = GetComponent<Rigidbody>();

can we use

Rigidbody rb = new Rigidbody();

and use methods based on that. will the be result same ?

Thankyou.

P.s : I am new to unity

1 Answers1

3

NO!

For your usecase though see the very last lines of this answer. ;)

It is completely illegal in Unity to use new for creating instances of a Component! You will also get a warning about it in the console.

For some stupid reason Unity still "allows" to do it though and does only throw a warning instead of an exception. However, that instance just will not "work" since most of things will not be initialized correctly.. and how should it? There is no GameObject related to it so what would the use of a Rigidbody without according GameObject be? - Right, it is absolutely useless ;)

A Component can only exist correctly if it is attached to a GameObject. Thus, there are only three valid ways of creating instances at runtime:

  • Use the constructor of GameObject like e.g.

     var obj = new GameObject("SomeName", typeof(Rigidbody));
     var rb = obj.GetComponent<Rigidbody>();
    

    This creates a new GameObject called SomeName with only the Transform and a Rigidbody component attached.

  • Use Instantiate to either clone an existing GameObject or create an instance from a prefab.

    [SerializeField] private Rigidbody prefab;
    
    ...
    
    var rb = Instantiate (prefab);
    
  • Use AddComponent to add a new instance of given component type to an existing GameObject. The example from the constructor can also be implemented as

    var rb = new GameObject("SomeName").AddComponent<Rigidbody>();
    

    or in your use case to add that component to the same object your script is attached to

     var rb = gameObject.AddComponent<Rigidbody>();
    

    which probably comes closest to what your code tries to do

derHugo
  • 83,094
  • 9
  • 75
  • 115