- Home /
Abstract Class acting like a static Class when inherited
Hello everyone! I am just getting started with development for touch interfaces and I decided to make a base class to contain all the functions I need and then inherit those functions whenever I want to use them. This is the script of the base class
using UnityEngine;
using System.Collections;
public abstract class TouchScreenBaseClass : MonoBehaviour {
public void ReadTouches(){
foreach(Touch t in Input.touches){
Ray ray = Camera.main.ScreenPointToRay(t.position);
RaycastHit hit;
if(Physics.Raycast(ray, out hit)){
if(t.phase.Equals(TouchPhase.Began)){
OnTouchDown();
}
if(t.phase.Equals(TouchPhase.Ended) || t.phase.Equals(TouchPhase.Canceled)){
OnTouchUp();
}
if(t.phase.Equals(TouchPhase.Stationary)|| t.phase.Equals(TouchPhase.Moved)){
OnTouchStay();
}
}
}
}
public virtual void OnTouchDown(){
}
public virtual void OnTouchUp(){
}
public virtual void OnTouchStay(){
}
}
After creating this class I created an other class which basically just changed the material of an object.
using UnityEngine;
using System.Collections;
public class Colors : TouchScreenBaseClass {
public Material m1;
public Material m2;
public Material m3;
void Update(){
ReadTouches ();
}
override public void OnTouchDown(){
gameObject.renderer.material = m1;
}
override public void OnTouchStay(){
gameObject.renderer.material = m2;
}
override public void OnTouchUp(){
gameObject.renderer.material = m3;
}
}
The problem is that if I have multiple cubes with this script when I touch any of the cubes they all change color as if some function in the script were static or something like that.
Any help on this matter or anything related to touchscreen inputs would be greatly appreciated, so thank you in advance.
Answer by NoseKills · Jun 06, 2014 at 07:58 PM
If you are calling ReadTouches()
in for example the Update()
method, that means all instances of TouchScreenBaseClass
are doing it all the time. So when you click on any object, the Physics.Raycast(ray, out hit)
in all the objects returns true and they all get switched.
In other words, i don't see any code in place that checks which specific object was clicked.
Furthermore, if you have plenty of objects running this script, you are doing quite a lot of raycasts. Maybe have a "Manager" script and do the raycast in it's Update()
then find out which object was clicked based on the hit info, and call the appropriate method only on that object.
Your answer
Follow this Question
Related Questions
How to work with a list of base class, if a variable is only found in some subclasses? 2 Answers
How to use of interfaces and inheritance if you have seperated scripts? 0 Answers
Accessing interface in a derived class through the parent class 0 Answers
Having static classes inherit from a static class 1 Answer
Overriding a subtype's variable with its own subtype 1 Answer