- Home /
C# Inheritance Problems
Im trying to pull variables and their values from the parent script into the child script, but i keep getting these errors.
Assets/Scripts/shieldControl.cs(15,51): error CS0120: An object reference is required to access non-static member
UnityEngine.Component.transform' > > > Assets/Scripts/shieldControl.cs(17,34): > error CS0120: An object reference is > required to access non-static member >
PlayerControl.playerShieldActive'
Here is the Current Code for the Child Script
I am trying to pull the transform.position of the parent object for placement of the child object when it is called, and i am trying to pull the bool from the parent as a check on whether the object is being called.
using UnityEngine;
using System.Collections;
public class shieldControl : PlayerControl {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
Vector3 shieldPos = transform.position;
Vector3 playerPos = PlayerControl.transform.position;
if(PlayerControl.playerShieldActive == true){
shieldPos = playerPos;
}
else{
shieldPos = new Vector3(100f,100f,100f);
}
}
}
Answer by whydoidoit · Jul 01, 2012 at 08:34 PM
When you inherit like that there is no need to refer to PlayerControl - you already have all of its variables right there.
e.g. Vector3 playerPos = transform.position;
it fixed the errors but its not updating the variables. playerShieldActive stays false, even when it is true in the parent script.
You've got to have something else wrong - that would work if the base class had its value true.
Are you sure that it is true in the instance of this object? Subclasses just share definitions, not values - if you have something else which is a PlayerControl it will not change the values of something which is shieldControl.
is there any way to have shieldControl inherit the actual values from PlayerControl?
No - if you wanted to have it read values from another object then you need to have a reference to that object in shieldControl and use that to get them:
public PlayerControl playerControl; //Set this in the inspector
if(playerControl.playerShieldActive)
I don't think you are looking for inheritance (which is the ability to have two objects share a definition of a variable or a method) - you are looking for composition - which means having references to the other things.
Your answer
Follow this Question
Related Questions
An OS design issue: File types associated with their appropriate programs 1 Answer
[C#] Calling a method of a child class on a parent object 1 Answer
Make a simple tree 1 Answer
How can I listen for a function being called from a parent class? 1 Answer
Inheriting Parent Rotation and position 2 Answers