Hi there,
I’ve two scripts
public abstract class ItemAction : MonoBehaviour
{
/// <summary>
/// This is false ONLY the first time I run the app
/// </summary>
bool initialized;
public void Initialize()
{
Debug.Log($"ItemAction Initialize() -> initialized: {initialized}");
// initialized is false ONLY the first time I run the app
if (initialized)
{
Debug.LogWarning($"Already initialized");
return;
}
Debug.Log($"Initializing ...");
initialized = true;
Init();
}
protected virtual void Init()
{
Debug.Log($"ItemAction: Init()");
}
}
and here is a concrete class of ItemAction
public class DoShot : ItemAction
{
protected override void Init()
{
Debug.Log($"DoShot: Init()");
}
}
I’ve this ScriptableObject where I have a reference to an ItemAction
[CreateAssetMenu]
public class ItemActionReference : ScriptableObject
{
public Sprite sprite;
public ItemAction action;
}
So I’ve created an asset (in the Resources folder) of type ItemActionReference and assigned to it a prefab which contains the script DoShot.
I’ve another script that load the Asset LevelItemActions created in the Resources folder and call the Initialize() method of ItemAction script
public class ResLoader : MonoBehaviour
{
LevelItemActions levelItemActions;
void Start()
{
if (!levelItemActions)
levelItemActions = Resources.Load<LevelItemActions>("LevelItemActions");
levelItemActions.actions[0].action.Initialize();
}
}
When I run the game the first time it works as expected. When called the method ItemAction.Initialize() the variable initialized in ItemAction is false and is initialized to true but the second time I run the game the variable initialized is true so it’s not initialized and the method ItemAction.Init() is not called.
I really have no idea why is this happening.
How is possible that the variable initialized is true when I run the app a second time? A boolean variable is false by default!
Also is a good practice to use a prefab in the way I’m using it? I’ve created the prefab only because is the way I found to reference the script DoShot in the ShotAction asset.
Any help will be appreciated!
This game was created using Unity 2018.4.23f1 but I tested it using Unity 2019.4.0f1 and I get the same behaviour in both versions. I’m working with Windows 10x64 Version 1909 (OS Build 18363.836).
I’ve uploaded the whole project (a very small runnable project) no executables, only source code because I think it’s easier to analyze and debug a runnable project than analyzing the code posted here.