- Home /
Call a function on a script attached to an object
Hi guys,
So, I have a raycaster, and when it hits an object, I want to call a function in the script attached to that object.
Raycast and the (attempt) to call function:
void Update ()
{
Vector2 emitter = transform.position + transform.up*1.5f;
RaycastHit2D hit = Physics2D.Raycast (emitter, transform.up);
if (Input.GetKey (KeyCode.Space) & hit != null)
{
hit.collider.gameObject.GetComponent(SpaceThing).Damage(10,0);
}
}
The function I am attempting to call, in the script called "SpaceThing":
public void Damage (float damage, float penetration)
{
float mitigation = Mathf.Max(0, (armor-penetration));
health = health - (damage-mitigation);
}
However, when I try to run, I get error CS0119: Expression denotes a 'type' where a 'variable', 'value', or 'method group' was expected
I can't figure out why it's doing that :/ Thanks!
Answer by highpockets · Mar 04, 2014 at 04:59 PM
GetComponent in C # is not used correctly, change this:
hit.collider.gameObject.GetComponent(SpaceThing).Damage(10,0);
to this:
hit.collider.gameObject.GetComponent<SpaceThing>().Damage(10,0);
Awesome, works perfectly. I'm still getting used to the nuances of coding... Thanks for taking the time to answer, it's much appreciated!
The problem is that the normal version returns a Component and this does not know about Damage. You can go around it if you want to make life complicated:
((SpaceThing)hit.collider.gameObject.GetComponent(SpaceThing)).Damage(10,0);
Interesting. Always good to have options, I suppose. I'm not clear on the structure there though; what does the first reference to SpaceThing do?
Your answer
![](https://koobas.hobune.stream/wayback/20220613135347im_/https://answers.unity.com/themes/thub/images/avi.jpg)