- Home /
How to get "transform.position" from Base Class in realtime
Hi, i have a Baseclass Player, and three Suclasses (Enemy, Teammate, Keeper). Every Subclass needs to know it's own unique Position with "transform.position" and the Position from the Baseclass. I found some working solutions like: unique Variables per Class (playerPos, enemyPos, etc.) or static private Variables with the name "position" in all 4 Classes with a get Property.
BUT my question is, is there a Way to declare a non-static protected Variable "position" in the Baseclass which the subclasses can use (derive) for their own Positions? And then to compare the Positions in Realtime (void Update)?.
Example:
public class Player : MonoBehaviour {
protected Vector3 position;
void Update() {
Position();
}
protected Vector3 Position() {
position = transform.position;
return position;
}
}
public class Enemy : Player {
if (base.Position().x == this.Position().x) {
// Do something
}
}
Yes. I'm Trying to get the position from the parentclass. Is there a way unity or csharp can manage this?
Can you explain more what "subclasses can use (derive) for their own Positions" is trying to accomplish? Why can't you directly access transform.position
from child classes? Are you trying to cache the position for performance?
if you want a parent, then create the new game objects and set their transform.parent
to the parent object.
inheriting from a class is different from creating a parent object - if you don't actually create the parent like that, it won't have one.
I have already Solutions for this, my question is more general. -- I want ONE Vector3 Variable (Non-Static and protected) in the Baseclass, called position. i want that my derived classes also use this Variable but for their OWN Positions. -- So Far this works normally.
Now i want to check the Position of the Class Player (Baseclass) out of the Class Enemy without creating an Instance. Is this possible?. It is possible with static Variables.
Answer by hexagonius · Dec 09, 2014 at 09:08 PM
If you want to access a script variable that is not related to an object (instantiation), you must define it as static, no chance to do this any other way. BUT the major problem is ONLY gameobjects, which are instances, have transforms and therefore positions. Without an instance of those, no position. The static version would also mean you instantiated only one copy, but then static would be useless, since you instantiate anyway and then you could just read its transform.position directly.
Answer by braco86 · Dec 10, 2014 at 12:56 PM
Thank you hexagonius! Now i get it and i am able to do that what i was looking for!