简体   繁体   English

Unity,实例化预制上的类在对象之间是不同的

[英]Unity, Class on instantiated prefab is different between objects

Odd question here - I have a gameobject with a class object attached. 奇怪的问题-我有一个附有类对象的游戏对象。 I instantiate the gameobject, and assign the class object with data from an existing class. 我实例化游戏对象,并为类对象分配来自现有类的数据。

I then instantiate a second gameobject with the exact same class object attached and assign it the same data as the first object. 然后,我实例化一个附加了完全相同的类对象的第二个游戏对象,并为其分配与第一个对象相同的数据。 If I modify the class attached to the first gameobject, it is different to the class attached to the second object, even though they both reference (or should) reference the same original class. 如果我修改附加到第一个游戏对象的类,则它不同于附加到第二个游戏对象的类,即使它们都引用(或应该)引用相同的原始类。

Can anyone think why this would happen? 谁能想到为什么会这样?

if you make the variables you want to persist in the class your adding static, it will use the same instance for both cases, modifying both when you mod one. 如果您要添加要在类中持久化的变量,则添加静态对象时,这两种情况都将使用相同的实例,而在修改时会同时修改两者。

check out this enemy class from unity3d's own dev pages 从unity3d自己的开发页面中查看这个敌人的职业

https://unity3d.com/learn/tutorials/topics/scripting/statics https://unity3d.com/learn/tutorials/topics/scripting/statics

using UnityEngine; 使用UnityEngine; using System.Collections; 使用System.Collections;

public class Enemy
{
//Static variables are shared across all instances
//of a class.
public static int enemyCount = 0;

public Enemy()
{
    //Increment the static variable to know how many
    //objects of this class have been created.
    enemyCount++;
}
}

They are different instances of the same class, they don't reference the same class. 它们是同一类的不同实例,它们没有引用同一类。 You should write a duplicate method to duplicate the values 您应该编写一个重复方法来重复值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM