0

In following code, AnotherScript is attached to the same game object so if i want to access playerScore in AnotherScript why i use GetComponent in awake function? can i just declare the instance of class anotherScript = new AnotherScript() to access the playerScore? Hope my question is clear .. thanks

using UnityEngine;
using System.Collections;

public class UsingOtherComponents : MonoBehaviour
{ 
    private AnotherScript anotherScript;

    void Awake ()
    {
        anotherScript = GetComponent<AnotherScript>();
    } 

    void Start ()
    {
        Debug.Log("The player's score is " + anotherScript.playerScore);

    }
}
derHugo
  • 83,094
  • 9
  • 75
  • 115
alvin123
  • 79
  • 2
  • 8
  • Unity uses component paradigm so it makes sense to add or remove component. The duplicate explains what happens if you do this the other way. – Programmer Aug 23 '17 at 19:24

2 Answers2

1

If you look through documentation you'll see that MonoBehaviour constructor can present in script but it also has a lot of restrictions. For example, you cannot have any params in it. Also it's very convenient to have ability to set up component's parameters via inspector. It's especially useful when it's done by non-programmers because you don't have to change code to modify gameobject's behaviour.

Also there is a reason why Unity has so complex relations with script's constructors: it's because every gameobject and other stuff Unity does (rendering, sound, etc) in terms of memory is driven by Unity itself and scripts memory management is done by the c# garbage collector. So to avoid troubles which may occur while creating components earlier that gameobject is actually created on scene or removing gameobject from memory before it's components are removed restrictions with constructors and destructors exists. This functionality is hidden inside Unity by implementing monobehaviour methods like Start(), Awake(), Destroy().

The last thing to add is that if you work with pure c# classes in Unity (non mono inherited) you can use constructors as you wish, because you don't have this memory management problem. And if your custom fuctionality doesn't need to have any MonoBehaviour functionality (if you don't want them to be attached to any gameobject) it's more preferable to use pure c# class.

vmchar
  • 1,314
  • 11
  • 15
1

It also worth considerating that any other GameObject can have a AnotherScript attached to it (and maybe more than one instance actually).

When you write private AnotherScript anotherScript;, you just declare a reference to an AnotherScript instance, and this can refer to any AnotherScript instance from any GameObject.

By using GetComponent in the Awake function, you specify precisely which instance you want to refer to, this is to say : the first one attached to the same GameObject that the current instance of UsingOtherComponents is attached to.

Pierre Baret
  • 1,773
  • 2
  • 17
  • 35