Script runs on Start. Need it to run when GameObject is enabled.

I’m a complete novice at scripting but I created this script that generates a random word from a string when the game starts. I just want it to generate a new word everytime the game object is turned off and then turned back on. Can anyone help?

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

public class GenerateWords : MonoBehaviour {

    public TextMesh question;
    string[] words = new string[] {"Alpha Centauri","apogee","asteroid","astronaut","astronomer","astronomy","background radiation","binary star","black hole","Ccluster","comet","conjunction","constellation","corona","cosmonaut","crater","dark matter","day","dwarf planet","Earth","eclipse","ecliptic","escape velocity","flare","galaxy","geosynchronous","gibbous","hydrogen","helium","Hubble","ionosphere","Jupiter","Kepler","Kuiper","light-year","local group","lunar","magnitude","Mars","mass","Mercury","meteor","meteor shower","meteorite","meteoroid","Milky Way","moon","nadir","NASA","nebula","Neptune","neutron star","nova","observatory","Oort","opposition","orbit","parallax","parsec","penumbra","perigee","perihelion","perturbation","phase","planet","planetary nebula","planetoid","Pluto","pulsar","quasar","radiant","radiation","revolve","rocket","satellite","shooting star","solar","solar system","solar wind","solstice","space","space station","star","sun","sunspot","supernova","telemetry","telescope","umbra","Uranus","vacuum","Van Allen belt","Venus"};

    // Use this for initialization
    void Start () {

        question.text = words[Random.Range(0, words.Length - 1)];

    }
   
    // Update is called once per frame
    void Update () {
       
    }
}

Instead of using Start(), use OnEnable()

You can find a lot of other useful functions in the MonoBehaviour API

1 Like

Thanks for the reply. I actually tried that before and it didn’t work. I just replaced the Start() with OnEnable(). I was wondering if I needed to add something somewhere else?

Just using OnEnable() ought to work. If it’s not working, it’s time to start doing standard debugging techniques, like checking your console for errors and adding Debug.Log statements to test if the function is being called (maybe in both Start and OnEnable).

I was enabeling the text mesh object not the object with the script attached. It works. Thanks!