- Home /
,How can I reference all game objects with a tag including clones
,I am trying to create a game where you need to push blocks off of a platform, and after a few seconds, a new block spawns that is the clone of the first one. My issue is that when I push a block off the edge, it only counts score for the first one (It counts score when it hits a certain X value), I have tried to make all of the blocks under a tag, and it still only counts the first one when it falls off. I feel like this is really easy to fix, but I am just missing something.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Score : MonoBehaviour
{
public GameObject box;
public int scoreValue = 50;
public Text score;
// Start is called before the first frame update
void Start()
{
box = GameObject.FindGameObjectsWithTag("clone");
score = GetComponent<Text>();
}
void Update()
{
if (box.transform.position.y <= -9.5 && box.transform.position.x < 23)
{
score.text = "" + scoreValue.ToString();
}
if (box.transform.position.y <= -9.6 && box.transform.position.x < 23)
{
box.transform.position = new Vector2(50,50);
}
}
}
Answer by logicandchaos · Aug 10, 2021 at 04:04 PM
ok what you did was make this variable, a single gameObject, public GameObject box;
and then try to populate it with this: box = GameObject.FindGameObjectsWithTag("clone");
Because it is only a single variable you only get the 1st object returned. You need to create a list or array to put the variables in.
public List<GameObject> boxes;
or
public GameObject[] boxes;
Then you access the ones you want like this:
boxes[1]
boxes[10]
whatever you want!
or loop through the list if you want to effect all boxes. Arrays and loops are the bases of programming.
Your answer
![](https://koobas.hobune.stream/wayback/20220613041458im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
C# change an object tag wit raycasthit. 2 Answers
Finding the position of an object 1 Answer
how do i make an Enemy take damage from prefab bullet clone? 1 Answer