Justin P
Justin P

Reputation: 13

Use copies of a variable rather than reference

I'm trying to access a copy of a variable, rather than the variable itself. For example, I want an enemy to drop a certain quantity of Bones when killed.

Enemy1: Drop 1 of Bones

Enemy2: Drop 2 of Bones

Rather than recreate this Item 'Bones' for every kind of enemy, I want to have one class that contains all Items, and enemies such as Enemy1 and Enemy2 can use AllItems.Bones to get the Bones drop. The problem occurs when I want to change the quantity variable of the drop object in Enemy2.cs. When I do 'drop.quantity = 2', the quantity of Enemy1's drop becomes 2 as well. Here's about the code I'm using:

//AllItems.cs
public class AllItems{
    public static Item Bones = new Item();
}

//Item.cs
public class Item{
    public int quantity = 1;
}

//Enemy1.cs
public class Enemy1{
    Item drop;
    public Enemy1(){
        drop = AllItems.bones;
    }
}

//Enemy2.cs
public class Enemy2{
    Item drop;
    public Enemy2(){
        drop = AllItems.bones;
        drop.quantity = 2;
    }
}

Is there a way to set Enemy1's and Enemy2's Drop to AllItems.Bones and modify their drop without affecting the other's?

If there's a simple solution, my apologies. I've been looking for a long while now without success. I can give any additional info about why I'm doing something a certain way or how something is set up upon request.

Thank you.

Upvotes: 1

Views: 48

Answers (2)

Sourav Gupta
Sourav Gupta

Reputation: 86

Actually, when you use a static field or property, it shares only one instance everywhere. Instead, I would suggest you to make it non-static. Following should do the trick.

//AllItems.cs
public class AllItems
{
    public static Item GetBones()
    {
        return new Item();
    }
}

Please let me know in case of any confusion.

Upvotes: 1

Ofir Winegarten
Ofir Winegarten

Reputation: 9365

First you can simply change the = to => in the property:

public static Item Bones => new Item();

This will create new Item each time it's accessed.

But i would rather create a function for creating a new set of bones - IMO it would be more intuitive and clear:

public class AllItems{
    public static Item CreateNewSetOfBones()
    { 
        return new Item();
    }
}

Or the short syntax:

public class AllItems{
    public static Item CreateNewSetOfBones() => new Item();
}

Upvotes: 2

Related Questions