0

How to approach, from the second script, to a variable lights [currentIndex] which is the array? Sorry for the bad English Thank you for advice

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LightSwitchObj : MonoBehaviour {

     public  GameObject[] lights;
     public static int currentIndex = 0;
     float elapsedTime = 0f; // Counts up to repeatTime
     float repeatTime = 2f; // Time taken to repeat in seconds
 
 
            void Update(){
                  elapsedTime += Time.deltaTime;
         if (elapsedTime >= repeatTime)
         {
           NewRandomObject();
           elapsedTime -= repeatTime;
                    }
     }
     public void NewRandomObject()
     {
         int newIndex = Random.Range(0, lights.Length);
         // Deactivate old gameobject
       lights[currentIndex].SetActive(false);
         // Activate new gameobject
         currentIndex = newIndex;
        lights[currentIndex].SetActive(true);
     }}
Juraj Juraj
  • 19
  • 1
  • 5
  • Does this answer your question? [Accessing a variable from another script C#](https://stackoverflow.com/questions/25930919/accessing-a-variable-from-another-script-c-sharp) – Remy Jul 21 '20 at 07:03

2 Answers2

1

this is very simple way:

  • Make a new script call it anything you want
  • Make a public variable and call it LightSwitchObj
  • in this new script you can access the array of the lights gameobject since its a public array variable as well
  • Attach the new script to a new gameobject
  • Drag and drop the gameobject that has the first script to assign it to the reference of the new script

and this should work

VectorX
  • 657
  • 5
  • 12
0
  • You can using Singleton to acess varible from anywhere.
  • Using static varible
  • Using UI/Light Manager to save it.
Tài Lê
  • 63
  • 1
  • 10