- Home /
declaring unknown script components under a empty variable
in this code: using UnityEngine; using System.Collections;
public class example : MonoBehaviour {
void Update() {
OtherScript otherScript = GetComponent<OtherScript>();
otherScript.DoSomething();
}
}
is there a way so that i can declare a empty variable for the OtherScript part? for example what would be the appropriate variable type in this code?:
using UnityEngine;
using System.Collections;
public class example : MonoBehaviour {
public /*variable type?*/ otherScript;
void Start() {
OtherScript otherScript = GetComponent<OtherScript>();
}
void Update() {
otherScript.DoSomething();
}
}
it's just OtherScript
public class example : $$anonymous$$onoBehaviour {
public OtherScript otherScript;
void Start() {
otherScript = GetComponent<OtherScript>();
}
void Update() {
otherScript.DoSomething();
}
}
what if the OtherScript might apply to different scripts under different circumstances? for example, OtherScript might have to be a script called ScriptA while other times, it might have to read from ScriptB or even ScriptC?
Have you tried "Component"?
Component otherScript = GetComponent<OtherScript>();
I'm just assu$$anonymous$$g that if this works, you'd probably have to specify the script type manually each time you try to call a method/function...
otherScript<movement>.walk(); //just an example
http://docs.unity3d.com/Documentation/ScriptReference/Component.html
You could try reflection, but I'm not sure how great that would be performance wise..
What exactly are you trying to do? Perhaps ther's a simpler solution to your problem.
Like using a interface or inheritance
im trying to make it so that i can use teh same damage calculation function script for multiple types of bullets colliding with multiple types of enemies. so basically, i want it so that i can use the same script when bullet 1 hits enemy A as well as when bullet 1 hits enemy B, bullet 2 hits enemy A, etc. and returns the damage dealt after the script reads the current hp of the enemy, the enemys armor value, etc.
so basically all you need are 2 scripts, 1 on the bullet, 1 on the enemy with just different settings for the variables, correct?
so something like (just an example):
class Bullet {
int damage = 3;//some default value
}
class enemyHP {
int hp = 100;
public void doDamage(int dmg) {
hp -= dmg;
if(hp < 0) {
//enemy dies...
}
}
}
you'd put those on each enemy and bullet and just change the Bullet.damage and the enemyHP.doDamage(..) function would take care of calculating how much damage the enemy receives..
and on the bullet you'd probably also want to check for the collision and apply the damage.. so something like
void onCollisionEnter(Collision col){
if(col.collider.getComponent<enemyHP> != null){
col.collider.getComponent<enemyHP>.doDamage(Bullet.damage);
}
}
hope you get the idea.. there are obviously other ways to do it , but this would be 1 way of handling it