- Home /
The question is answered, right answer was accepted
Override Function Scope
I'm having some trouble accessing an instance variable in an overridden function after setting it in the start function.
The Debug.Log just returns that the level is still 3 inside of Activate_Skill() but it returns 5 inside of the update function. How do I get the same value inside of Activate_Skill()?
I have tried changing the variable to public, and declaring it in the base class, initializing it to 5 in the base class start function etc,
public class SubClass : BaseClass
{
private int level = 3;
private void Start()
{
level = 5;
}
private void Update()
{
Debug.Log("level: " + level);
}
public override void Activate_Skill()
{
Debug.Log("Level: " + level);
}
}
public abstract class BaseClass : MonoBehavior
{
public abstract void Activate_Skill();
}
Answer by ItsBoats · Jun 26, 2017 at 08:11 AM
The problem turned out to be that I was basically calling Activate_Skill() in a prefab object instead of the instanced object. So while I was seeing that there was an instance of the object from the debug message in the update function, I was calling the Activate_Skill() function from the prefab object which obviously never executed its Start() function. The above code was pretty irrelevant to the issue, but I figured it was that I was doing something horribly wrong with the abstract/override keywords
Answer by Bunny83 · Jun 25, 2017 at 01:21 AM
Well, you clearly call your Activate Skill method before your Start method is called. Start is called quite late. It's called right before Update.
Instead of Start() use Awake()
I'm calling it in the update function of my player controller script after a keypress, so it is well after Start() and Awake()
Thank you for pointing that out, it should have said that in the topic question already. Updated code above to reflect that.
Follow this Question
Related Questions
Overriding an initial value in a subclass? 3 Answers
Question about Overriding 1 Answer
Overriding an inherited Enum? 1 Answer
Help with override function in inheritance,HELP with inheritance overide functions 0 Answers
An OS design issue: File types associated with their appropriate programs 1 Answer