Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question about creating a reference to a script in another script

Discussion in 'Scripting' started by segasega89, Apr 14, 2020.

  1. segasega89

    segasega89

    Joined:
    Feb 10, 2019
    Posts:
    48
    Hi there,

    I'm following a tutorial at the moment on Youtube and early on in the video the tutor creates two scripts(a Player.cs script and a Controller2D.cs script).

    In the player.cs script he creates a reference to the Controller2D.cs script by writing:
    Code (CSharp):
    1. Controller2D controller;
    My understanding is that the variable called " controller" will allow access to the Controller2D script but what is the "Controller2D" that precedes controller? Is it a kind of data type?

    The fully written code is shown here:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. [RequireComponent(typeof(Controller2D))]
    6.  
    7. public class Player : MonoBehaviour
    8. {
    9.     Controller2D controller;
    10.     // Start is called before the first frame update
    11.     void Start()
    12.     {
    13.         controller = GetComponent<Controller2D>();
    14.     }
    15.  
    16.     // Update is called once per frame
    17.     void Update()
    18.     {
    19.        
    20.     }
    21. }
    22.  

    As you can see he gets access to the Controller2D script in the Start function by using the GetComponent function.

    Any help would be appreciated.

    Thanks
     
  2. ThySpektre

    ThySpektre

    Joined:
    Mar 15, 2016
    Posts:
    362
    Controller2D is a class. (What you refer to as a data type).

    Classes are blueprints that can make objects.

    Controller2D is a class. The instance of that class (the object) has a handle to it created by:

    controller = GetComponent<Controller2D>();
     
  3. ThySpektre

    ThySpektre

    Joined:
    Mar 15, 2016
    Posts:
    362
    Data types may be built in, such as int or floats, or user defined, such as structs or classes or interfaces.

    You can also classify data types as Value Types which store values, or Reference Types which store a reference to the data.
     
  4. segasega89

    segasega89

    Joined:
    Feb 10, 2019
    Posts:
    48
    Thanks for the helpful replies.
    Am I right in saying that the variable "controller" in my original post is considered an instance of the Controller2D class?
     
  5. ThySpektre

    ThySpektre

    Joined:
    Mar 15, 2016
    Posts:
    362
    The variable "controller" holds "handle" to the instance of the Controller2D class (the object), after the GetComponent statement.