我正在编写代码,我认为一切都很好,然后测试了我的代码。 在代码中,我正在更改值:
ennemy.object_infos[0] = "Ennemy";
player.object_infos[0] = "Player";
和
的输出 Console.WriteLine(player.object_infos[0])
是“敌人”,输出是
Console.WriteLine(ennemi.object_infos[0])
是“敌人”
确切的代码是:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
public class Program
{
public static void Main()
{
GameEngine game = new GameEngine();
GameEngine.GameObject ennemy = new GameEngine.GameObject();
GameEngine.GameObject player = new GameEngine.GameObject();
ennemy.object_infos = GameEngine.GameObject.object_infos_default;
player.object_infos = GameEngine.GameObject.object_infos_default;
ennemy.object_infos[0] = "Ennemy";
player.object_infos[0] = "Player";
Console.WriteLine(ennemy.object_infos[0] + "," + player.object_infos[0]);
}
}
public class GameEngine
{
public List<GameObject> objects = new List<GameObject>();
/*
Vector2 : vector with 2 values x,y
*/
public struct Vector2
{
public float x,y;
public Vector2(float xaxis,float yaxis)
{
x = xaxis;
y = yaxis;
}
}
public class GameObject
{
/*
object_infos indexes:
0 = name(string),
1 = id(double),
2 = sprite path in assets(string),
3 = transform (array of 3 vectors2)
4 = rectangle collider(Vector2 size w,h)
5 = isActive(bool)
6 = isVisible(bool)
7 = tag
*/
public object[] object_infos;
/*
transform default :
index 0 = position,
index 1 = rotation,
index 2 = scale
*/
private static Vector2[] transform_default = {new Vector2(0,0),new Vector2(0,0),new Vector2(1,1)};
/*
On new object creation apply this object infos
*/
public static object[] object_infos_default = {"New Object", 0, "/Assets/default.png", transform_default, new Vector2(1,1), true, true, "object"};
}
/*
engine class for all mathematics
*/
public class Math
{
/*
public static bool areColliding(Vector2 first_object_pos, Vector2 first_object_collidersize,Vector2 second_object_pos, Vector2 second_object_collidersize)
{
}
*/
}
}
真的很奇怪,我更改了一个值,而更改了两个值,请有人帮助我!
答案 0 :(得分:4)
ennemy.object_infos = GameEngine.GameObject.object_infos_default;
player.object_infos = GameEngine.GameObject.object_infos_default;
这会将object_infos_default
分配给 ennemy.object_infos
和player.object_infos
。由于分配的工作方式,您只分配了对该对象数组的引用。因此,两个object_infos
都引用相同的对象,它也是object_infos_default
所引用的相同对象。
因此,当您通过三个变量之一来更改对象时,您将同时为所有变量进行更改。
您应该改为创建副本,例如使用Array.clone
:
ennemy.object_infos = (object[])GameEngine.GameObject.object_infos_default.Clone();
player.object_infos = (object[])GameEngine.GameObject.object_infos_default.Clone();
答案 1 :(得分:0)
这并不奇怪,您的ennemy.object_infos和player.object_infos是同一对象,因此指向内存中的同一位置。因此,当您更改其中一项时,也会更改另一项。
如果您不希望发生这种情况,则需要为每个对象创建一个新对象。