as i know class type parameter is always passed as reference. but whenever i pass a class type variable which is class member as parameter. it always works like call by value.
public class MapGenerator : MonoBehaviour
{
[SerializeField]
private List<MapEntity> stageTerrains = new List<MapEntity>();
private MapEntity stageTerrain = new MapEntity();
private void Start()
{
RandomChoice(stageTerrains);
}
public void RandomChoice(MapEntity mapEntity)
{
mapEntity = stageTerrains[Random.Range(0,selectedList.Count)];
Print(mapEntity); //it always works well
Print(stageTerrain); // always print null
}
}
so i put an ref keyword to parameter and it works as call by reference
public class MapGenerator : MonoBehaviour
{
[SerializeField]
private List<MapEntity> stageTerrains = new List<MapEntity>();
private MapEntity stageTerrain = new MapEntity();
private void Start()
{
RandomChoice(ref stageTerrains);
}
public void RandomChoice(ref MapEntity mapEntity)
{
mapEntity = stageTerrains[Random.Range(0,selectedList.Count)];
Print(mapEntity); //it always works well
Print(stageTerrain); // print well too
}
}
i wonder why passing class type member as parameter is worked like call by value
From the ref documentation
So I'll try to explain the makes the formal parameter an alias as simple as possible.
Without ref
Imagine the
stageTerrainfromprivate MapEntity stageTerrain = new MapEntity();as a box holding an address.Imagine the
mapEntityfrompublic void RandomChoice(MapEntity mapEntity)as another NEW box.When you call the
RandomChoicethemapEntityis a new box holding the same memory address as thestageTerrainbox.Now
mapEntity = stageTerrains[Random.Range(0,selectedList.Count)];will assign the selected value only to the New box.With ref
Imagine the
mapEntityfrompublic void RandomChoice(ref MapEntity mapEntity)as an alias for an already existing box that will hold the memory reference just with a different name. (thus the alias statement)When you call the
RandomChoicethemapEntityis thestageTerrainbox.