Enable Component From Another Game Object Via Script

PSA: I’m a Unity noob and working through the Junior Programmer Pathway.

I have a StartGame method set to start my game after a difficulty button is pressed. That works fine. What I want to add is getting a game object (a starship) on the screen to move along the Z axis once the game starts. My thought processes for how to accomplish this keep getting stifled by confusion and/or lack of knowledge/experience.

My idea: Have my game manager script’s StartGame method enable a MoveObjectZ script component attached to the starship. But looking at solutions for this, they’re a bit beyond my comprehension so far. THIS post seems almost within reach, but I don’t really understand how it works…

That said, there’s probably a simpler solution I’m not aware of since it seems like there’s at least 5 different ways to reach the same goal in Unity scripting. So I guess I’m asking if anyone can explain how the solution I linked works, or share another way to go about this that’s less complicated.

You need to get a component only ? You can set a reference. So
declare a variable in your script of class-type e.g

private StartShipScript _startShip
  1. private means that the variable is accessible only for this script
  2. StartShipScript is the name / class of the other script
  3. _startship is the name of the variable

and in the Start/Awake method set up the references to get all the variables/function of the other script like this

void Start()
{
       _starShip = GetComponent<StartShipScript();
}
  • This allow you to get the single
    component of a gameobject (in the
    inspector there are components …
    :wink: in this case you get the all
    component => The script

  • GetComponent is one of the base of all your develop when you understand it you discover the fire.

  • Good Luck.

  • Then can add some code to understand
    what you need?

It’s that easy to reference a component from another object!? I have indeed discovered the fire, thank you!

And yeah, here’s my code presently. I set “starShip.enabled = true;” in the StartGame method, but that gives me the largest NullReferenceException I’ve ever seen:

GameManagerScript:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class GameManagerScript : MonoBehaviour
{
    public GameObject titleScreen;
    public bool isGameActive;
    public GameObject gameOverScreen;
    public GameObject[] asteroidPrefab;
    public GameObject powerupPrefab;
    private float spawnRangeX = 24;
    private float spawnPosY = 0;
    private float spawnPosZ = 20;
    private float startDelay = 2;
    private float asteroidSpawnInterval = 1.5f;
    private float powerupSpawnInterval = 15.0f;
    private StarshipScript starShip;

    // Start is called before the first frame update
    void Start()
    {
        isGameActive = false;
        starShip = GetComponent<StarshipScript>();
    }

    // Starts the game with difficulty from DifficultyButtonScript.cs, sets game to active, starts spawning objects, deactivates Title Screen objects
    public void StartGame(int difficulty)
    {
        asteroidSpawnInterval = asteroidSpawnInterval / difficulty;
        isGameActive = true;
        StartCoroutine(SpawnAsteroid());
        StartCoroutine(SpawnPowerup());
        titleScreen.SetActive(false);
        starShip.enabled = true;
    }

    // Sets game to inactive and activates game over screen
    public void GameOver()
    {
        isGameActive = false;
        gameOverScreen.gameObject.SetActive(true);
    }

    // Restart game by reloading the scene
    public void RestartGame()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }

    // Spawns asteroid prefabs
    IEnumerator SpawnAsteroid()
    {
        while(isGameActive)
        {
            yield return new WaitForSeconds(asteroidSpawnInterval); // Waits seconds in between spawns
            int asteroidIndex = Random.Range(0, asteroidPrefab.Length); // Randomly spawns a type of asteroid
            Vector3 asteroidSpawnPos = new Vector3(Random.Range(-spawnRangeX, spawnRangeX), spawnPosY, spawnPosZ); // Random location for spawn
            InvokeRepeating("SpawnAsteroid", startDelay, asteroidSpawnInterval); // Repeats spawn with delay

            if(isGameActive) // <--Might be able to remove this and add the instantiate to the while-loop
            {
                Instantiate(asteroidPrefab[asteroidIndex], asteroidSpawnPos, asteroidPrefab[asteroidIndex].transform.rotation); // Spawns
            }
        }
    }

    // Spawns powerup prefab
    IEnumerator SpawnPowerup()
    {
        while(isGameActive)
        {
            yield return new WaitForSeconds(powerupSpawnInterval); // Waits seconds in between spawns
            Vector3 powerupSpawnPos = new Vector3(Random.Range(-spawnRangeX, spawnRangeX), spawnPosY, spawnPosZ); // Randomly spawns a type of asteroid
            InvokeRepeating("SpawnPowerup", startDelay, powerupSpawnInterval); // Repeats spawn with delay
            
            if(isGameActive) // <--Might be able to remove this and add the instantiate to the while-loop
            {
                Instantiate(powerupPrefab, powerupSpawnPos, powerupPrefab.gameObject.transform.rotation); // Spawns
            }
        }
    }
}

StarshipScript:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class StarshipScript : MonoBehaviour
{
    public float speed;
    private float southBound = -900.0f;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        // Moves the background via translate * time * speed variable
        transform.Translate(Vector3.forward * Time.deltaTime * speed, Space.World);

        // Destroys the background if it moves too far south
        if (transform.position.z < southBound)
        {
            Destroy(gameObject);
        }
    }
}

DifficultyButtonScript:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class DifficultyButtonScript : MonoBehaviour
{
    private Button button;
    private GameManagerScript gameManagerScript;
    public int difficulty;

    // Start is called before the first frame update
    void Start()
    {
        gameManagerScript = GameObject.Find("Game Manager").GetComponent<GameManagerScript>(); // Sets reference to GameManagerScript.cs
        button = GetComponent<Button>(); // Sets reference to the button component
        button.onClick.AddListener(SetDifficulty); // Listens for a click and then runs SetDifficulty method
    }

    // When a button is clicked, call the StartGame() method and pass it the difficulty value (1, 2, 3) from the button
    public void SetDifficulty()
    {
        gameManagerScript.StartGame(difficulty); // Passes in difficulty variable from GameManager.cs when a button is pressed
    }
}

NullReferenceException Error:

NullReferenceException: Object reference not set to an instance of an object
GameManagerScript.StartGame (System.Int32 difficulty) (at Assets/Scripts/GameManagerScript.cs:38)
DifficultyButtonScript.SetDifficulty () (at Assets/Scripts/DifficultyButtonScript.cs:23)
UnityEngine.Events.InvokableCall.Invoke () (at <40205bb2cb25478a9cb0f5e54cf11441>:0)
UnityEngine.Events.UnityEvent.Invoke () (at <40205bb2cb25478a9cb0f5e54cf11441>:0)
UnityEngine.UI.Button.Press () (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:70)
UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/UI/Core/Button.cs:114)
UnityEngine.EventSystems.ExecuteEvents.Execute (UnityEngine.EventSystems.IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:57)
UnityEngine.EventSystems.ExecuteEvents.Execute[T] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.ExecuteEvents+EventFunction`1[T1] functor) (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/ExecuteEvents.cs:272)
UnityEngine.EventSystems.EventSystem:Update() (at Library/PackageCache/com.unity.ugui@1.0.0/Runtime/EventSystem/EventSystem.cs:501)