Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Class equality

Discussion in 'Scripting' started by DarkX, Dec 29, 2015.

  1. DarkX

    DarkX

    Joined:
    Apr 6, 2014
    Posts:
    42
    Hey guys,

    i am creating a simple inventory,
    when i make one class B equal a class A, the class b will be always equal to the A

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System.Collections;
    4. [System.Serializable]
    5. public class Item{
    6.     public string itemName;
    7.     public string itemId;
    8.     public int amount;
    9. }
    10.  
    11. public class BasicScript : MonoBehaviour {
    12.     public Item item_a;
    13.     public Item item_b;
    14.     void Start () {
    15.         item_a = new Item ();
    16.         item_a.amount = 1;
    17.         item_a.itemName = "DefaultName";
    18.         item_a.itemId = "00000x";
    19.         item_b = item_a;
    20.     }
    21.     void Update () {
    22.         item_a.amount++;
    23.  
    24.         if(item_a.amount==item_b.amount)
    25.         {
    26.             Debug.LogError("Something is wrong");
    27.         }
    28.     }
    29. }
    30.  
    31.  
    someone know what are happening,

    thanks in advance
     
  2. _Adriaan

    _Adriaan

    Joined:
    Nov 12, 2009
    Posts:
    481
    You have stumbled upon the difference between a Class and a Struct! In short, assigning variables to classes copies the reference to that class, while assigning variables to structs copies the struct, giving it its own memory and reference.

    Change the Item class to struct and you're off to go!
     
    GarthSmith and DarkX like this.
  3. DarkX

    DarkX

    Joined:
    Apr 6, 2014
    Posts:
    42