My Scriptable Object script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu (fileName = "Hero", menuName = "Create HeroValuesAsset")]
public class HeroValues : ScriptableObject
{
ListsScript listsScript = new ListsScript();
[SerializeField]
private int heroHP;
[SerializeField]
private string heroName;
public int HeroHP
{
get
{
return heroHP;
}
}
public string HeroName
{
get
{
return heroName;
}
}
public void PassValue()
{
int heroHP1 = HeroHP;
listsScript.RecieveValue(heroHP1);
}
}
My ListsScript
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ListsScript
{
public static List<int> testList = new List<int>();
public static int listInt1;
public static void RecieveValue (int heroHP1)
{
listInt1 = heroHP1;
Debug.Log(listInt1 + " is the value of listInt1 in the RecieveValue method.");
testList.Add(listInt1);
TestCount();
}
public static void TestCount()
{
Debug.Log(testList.Count + " is the current .Count of the testList.");
}
}
What i tried to do:
I have made multiple SO assets that i have attached to UI Buttons via OnClick in the inspector and made them pass the SO asset value to the RecieveValue method. Each button has its own unique SO asset made via SO script attached to it. I pass them to the method to add those values to the testList.
What happened:
Before adding the static
modifier to the testList, listInt1, RecieveValue(), each button pressed would cause the RecieveValue to add the value to an individual list for each SO asset despite the RecieveValue method clearly adding the values to the testList.
What is happening now:
After adding the static
modifier to the testList, listInt1, RecieveValue(), each button pressed adds its value to the one unified testList, instead of each having a list for themselves. This is exactly what i intended to do.
This solution suits my intent, as i only need to have one of each of those members.
What confuses me:
While i understand the purpose of the static
modifier and what it does (taken from Microsofts C# reference: "Use the static modifier to declare a static member, which belongs to the type itself rather than to a specific object."), i don’t really understand how turning testList, listInt1, RecieveValue() into members that belong solely to the ListsScript type prevents SO values from being added to their individual testLists. I also don’t understand why even after assigning heroHP1 value to the listInt1 (before using a static modifier on the method and the list/instance variable) they have their own lists.
I understand that it might be a very basic question, but i’d rather try to understand why it solves the issue instead of leaving it as it is. Thank you for your answers.