- Home /
Inherited member variables not set to base value c#
Hi
I have a base class named Base that has a variable set in it to a value A second class inherits from this Base and im logging the variables value to the console in it but its not set to the value from Base, why? It recognises the member name, autocomplete will show me the member name before i have completed writing it, so it has been inherited, just not the value, why?
Any help would be appreciated, Thanks
Answer by iwaldrop · Feb 13, 2013 at 06:29 AM
Just because your inheriting class has the same member variables does not mean that it uses the value from a different instance of the base class. Something still has to set the instance of the extended class that you're using.
The real conclusion is: We can't say anything without seeing your two classes. Your description is way too general / unclear.
fair enough and sorry for not being clear, i wrote the question at about 1.30am :s
public class Base : $$anonymous$$onoBehaviour
{
public float lifespan;
// Use this for initialization
void Start ()
{
lifespan = 3.0f;
}
}
public class newClass : Base
{
// Use this for initialization
void Start ()
{
Debug.Log (lifespan); //this prints 0 not 3 like i thought it should
}
}
thanks for your time
That is to be expected. If you initialized lifespan in your declaration it would print '3'. There is a difference between the following;
public float lifespan = 3;
public float lifespan;
thanks that defiantly works (just tried it) but I read somewhere that variables should only be declared and not initialized out of the start function, is this true?
and one other question, why does it work when initialised at deceleration and not in start?
You should not limit yourself to declaring variables at runtime; the popular reason for doing so is either the value is only known at runtime or because the developer wants to $$anonymous$$imize their memory footprint and not allocate memory for variables they're not using.
The reason is works is because the value is initialized! The start method is only called once a class has been instantiated as an object, but a value assigned to as its declared will always instantiate with its value. You could change it to anything you want at runtime, of course.
Your answer
Follow this Question
Related Questions
An OS design issue: File types associated with their appropriate programs 1 Answer
How to make a custom class inherited from Unity's GUI? 0 Answers
C# Conception - Hide inherited members and functions 1 Answer
Can I/Should I call Awake() in parent class manually? 1 Answer
Parent Class variables in Child Class's Inspector (C#) 0 Answers