Hi everyone,
I’ve come across a weird issue. I hope I can make it clear with the following example:
Ok, I’m working on a turn based game, where I want to keep all players in a List<>, which can be viewed and edited in the inspector. I also want the current player to be referenced in a variable called “current”.
Now, the weird thing is that as soon as I reference a Player from the List<> into “current”,
current = players[index];
I can no longer edit that Player from the List<> displayed in the inspector. However, all other Players in the list CAN be edited. Why is that?
Please note that editing the player using its reference (current) updates it’s values in the list as expected. Editing values inside the script itself also works without a problem.
current.health= 10;
players[index].health = 20;
Obviously this isn’t much of a problem, but I am curious as to what I’m missing. Thanks for taking the time!
Code I’m using.
[System.Serializable]
public class Player
{
public float health;
public Player() {}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyClass : MonoBehaviour
{
public List<Player> players;
public Player current;
public int index = 0;
// Use this for initialization
private void Start()
{
players= new List<Player>();
for (int i = 0; i < 10; i++)
{
players.Add(new Player());
}
current = players[index];
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.LeftArrow))
{
index++;
current = players[index];
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
index--;
current = players[index];
}
}
}