So I’ve been learning a lot about how C# works and how that pertains to Unity in the past couple weeks and have been watching a tutorial by a youtube guy on which to springboard my own ideas, however I am kind of confused by this code that I created using theirs as a base to build from:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class NovaPerson : MonoBehaviour {
private BaseArcherPlayerClass newNova;
// Use this for initialization
void Start () {
CreateNova();
}
// Update is called once per frame
void Update () {
}
public void CreateNova()
{
newNova = new BaseArcherPlayerClass();
newNova.CharacterName = "Nova";
}
}
Basically, I have a character whose name would be Nova here, and I want them to be a specific instance of a BaseArcherPlayerClass (which I already defined in a separate script). So i feel like the way this is set up would work, but that every time the game would be started up, the stats of this character would default to the default values which are defined in the CreateNova() function which is called on start (which would get rid of stats gained by leveling up and weapons purchased)? Is there a way to fix this? Maybe something along the lines of DontDestroyOnLoad in a void Awake()? Sorry if I’m totally off on this stuff, since I’m still starting out with game dev, but I really appreciate all of your guy’s help!
Best place to do these little tweaks is the inspector.
But the problem simply appears to be one of order. A variable will take on the last value assigned to it. Here is the order they are normally assigned.
Values you assign when declaring the variable
Values in Awake
Values assigned immediately after creating the object
Values assigned in Start
Values assigned in other places in your code occur as that code is called
I believe its not an issue of order (so much), its a issue of lacking serialization. He’s talking about loading player progress from a previous play session. From whats shown you’re not saving the data to file and loading that file during play.
Look into the available serialization options, be it the options provided directly by unity or by saving.loading formatted data directly to/from file using typical C# serialization techniques, saving said files in UnityEngine.Application.datapath.
If you’re Instantiating this via code and any logic immediately following that instantiation (executing in the same frame) relies on newNova existing then use Awake. Otherwise Start is fine.
As a general rule Awake should be used for initialisation internal to the component. Start should be used for initialisation which relies on other components.