- Home /
Generic List No Sense Problem
Hello, i was making my inventory system for my game and then i had a problem, i created a new script just to make some test i face this no-sense problem:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Test : MonoBehaviour {
public List<Pig> johnPigList = new List<Pig>();
public List<Pig> peterPigList = new List<Pig>();
void Start () {
peterPigList = johnPigList;
}
void Update () {
if (Input.GetKeyDown(KeyCode.G))
johnPigList[0].quantity++;
}
}
[System.Serializable]
public class Pig
{
public int quantity;
}
ok, i have two generic lists, johnPigList and then peterPigList, at start peter list is equal to john list, thats ok, but then, when i change the quantity variable, the two list changes too, and this on my mind makes no sense because i defined that these two are equal in the start, so then they are two separed lists.
Answer by SirCrazyNugget · Aug 17, 2014 at 12:28 AM
on line 12 you're setting the reference of peterPigList to johnPigList, this doesn't clone it just changes the reference (thus losing any reference to the previous peterPigList.
If you want to just clone the list an not change the reference use
peterPigList = new List<Pig>(johnPigList);
Spend some time on google understanding the difference between reference types and value types. Will be well worth the effort.
sircrazy that doesnt work for me, i have errors.
i tried to put peterPigList = new List(johnPigList);
but is the same thing as peterPigList = johnPigList;
You probably need the generic type as well.
peterPigList = new List<Pig>(johnPigList);
Your answer
Follow this Question
Related Questions
Does genericList.Sort() go low to high? or high to low? - for ints/floats 1 Answer
Edit each Parameter Class on Function 1 Answer
A node in a childnode? 1 Answer
Collisions and Lists 1 Answer