hey i wonna do a detection and if i detect gameobject i want to get access to variable without knowing script’s name
It just doesn’t make sense to say that you literally want ANY GameObject to be capable of taking damage.
If you want to make it so that you can MAKE any GameObject capable of taking damage, then create a script to implement this functionality, and add it to any GameObject that you want to have the functionality. This is what the whole business of creating MonoBehaviour classes and adding them to GameObjects as components is about - making objects capable of exhibiting specific kinds of behaviour.
The script could be very generic, something as simple as this would work…
class DamageTaker : MonoBehaviour
{
public float damage;
}
When a collision is detected between something that can inflict damage and another GameObject, you would check that second GameObject for a DamageTaker component, and if you found one you could then modify its damage
value.
This is deliberately simplistic because you seem to be demonstrating a lack of this fundamental idea of creating and adding behaviour to GameObjects. But a simple class like this does have the benefit of being totally flexible, which seems to be what you’re after.
What you do with the damage
is another matter, and would be implemented in other classes. You could for example create a Player class and add a component of that type to same GameObject as the DamageTaker. This could for example check its Damage component’s damage
value in its Update function and do something with it (probably “consuming” the damage by then resetting it to zero). But you could create other classes which used the damage
value in different ways.
I’m not sure if that meant you figured it out? But if not here’s the easiest way:
#pragma strict
//THIS SCRIPT WOULD BE FOR THE THING ATTACKING THE PERSON
var damage = 100f;
function OnCollisionEnter (hit : Collision) {
if (hit.gameObject.tag == "Player") {
hit.transform.SendMessage("DealDamage", damage, SendMessageOptions.DontRequireReceiver);
//That code tells the player to do the function DealDamage and it transfer the damage variable over, but not permanatly
}
}
#pragma strict
//THIS SCRIPT WOULD BE FOR THE PLAYER
var health == 100f;
function DealDamage(damage : float) {
health -= damage; //damage variable is transfered to this line of code
}
It is kind of difficult to permanently transfer a variable, so most of the time it is better to combine scripts into one, but when dealing with player health/damage, or points then use something like this.
Sorry it’s in Java, everything should work as long as you change the variables to whatever they use in C# like public float damage = 100; and I think you have to add something into the front of the function like void? I don’t know but you know so good luck.