I’m new at using Unity with C# and help is really appreciated.
I have two scripts. One that instantiates a gameobject prefab when I press spacebar key and adds it to a list. I can also cycle through the list with left/right arrow keys. (seems to work fine)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeSelector : MonoBehaviour
{
Vector2 CubeSpawnPosition;
public GameObject CubeObject;
public GameObject SelectedCubeObject;
public int CurrentCubeInList;
public List<GameObject> CubeList = new List<GameObject>();
// Start is called before the first frame update
void Start()
{
CubeSpawnPosition = new Vector2(5, 10);
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown("right"))
{
CurrentCubeInList += 1;
}
if (Input.GetKeyDown("left"))
{
CurrentCubeInList -= 1;
}
if (CurrentCubeInList >= CubeList.Count)
{
CurrentCubeInList = 0;
}
if (CurrentCubeInList < 0)
{
CurrentCubeInList = CubeList.Count - 1;
}
SelectedCubeObject = CubeList[CurrentCubeInList];
if (Input.GetKeyDown("space"))
{
Instantiate(CubeObject, CubeSpawnPosition, Quaternion.identity);
foreach (GameObject thisCube in GameObject.FindGameObjectsWithTag("Cube"))
{
CubeList.Add(thisCube);
}
}
}
}
and I have another script that controls the gameobjects movement which is attached as a component to the gameobject prefab and so also all clones of that prefab individually.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeController : MonoBehaviour
{
private Vector3 CubeTarget;
private float CubeSpeed = 3f;
CubeSelector CubeSelectorScript;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
if (gameObject == CubeSelectorScript.SelectedCubeObject)
{
CubeTarget = Camera.main.ScreenToWorldPoint(Input.mousePosition);
CubeTarget.z = transform.position.z;
CubeTarget.y = transform.position.y;
transform.position = Vector3.MoveTowards(transform.position, CubeTarget, CubeSpeed * Time.deltaTime);
Debug.Log("Cube at " + CubeSelectorScript.CurrentCubeInList + " Moved.");
}
}
}
}
What I’m trying to figure out is how to make it so that ONLY gameobjects that are currently selected in the other script’s list (from cycling through the list) will do the movement. any help is appreciated