Quantcast
Channel: Latest Questions by PokeJoe
Viewing all articles
Browse latest Browse all 20

How do I pass a consistent List between objects?

$
0
0
I am making a game which involves dynamically instantiated boxes. One box is added to the game every 0.2 seconds, but when the game starts there are no boxes. I want to make it so that when a box is clicked, it adds an explosive force to every other existing box in the game. So I have a spawner object, and a box prefab. The spawner is a cube with a component that instantiates the box prefab inside its own volume. The box prefab has an OnMouseDown method that should cause the explosion, but I am having trouble getting a list of all the other existing boxes into this method so I can add the force. As a solution, I created another game object called GameInfo that should contain general game information, such as score, the list of live boxes which I need for this problem, etc. Here is the relevant code. GameInfo.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class GameInfo : MonoBehaviour { public List liveBoxes; public int score = 0; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } } SpawnBoxes.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class SpawnBoxes : MonoBehaviour { //... private GameObject nextbox; public GameObject spawnee; //Box object goes here public GameObject LiveBoxCollector; //GameInfo object goes here void Update () { //...timing and setting box properties, etc. nextbox = Instantiate(spawnee,nextpos,Random.rotation) as GameObject; GameInfo info = LiveBoxCollector.GetComponent("GameInfo") as GameInfo; info.liveBoxes.Add(nextbox); } } BoxProperties.cs using UnityEngine; using System.Collections; using System.Collections.Generic; public class BoxProperties : MonoBehaviour { public GameObject GameInfo; private GameInfo info; public float BombForce = 3f; public float BombRadius = 8f; //... void Start () { info = GameInfo.GetComponent("GameInfo") as GameInfo; } //... void OnMouseDown() { print(info.liveBoxes.Count); foreach (GameObject i in info.liveBoxes) { i.rigidbody.AddExplosionForce(BombForce,transform.position,BombRadius); } However, this doesn't work. The line that is supposed to print the number of live boxes in the game always prints 0. That leads me to believe that there is some problem with passing the list of live boxes around between the GameInfo object and the two objects that use it. How can I make this information available to the OnMouseDown method so that I can add the force to all boxes?

Viewing all articles
Browse latest Browse all 20

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>