Answer the question
In order to leave comments, you need to log in
Why is Unity throwing error cs0411?
I'm learning Unity from Unity in Action. I am writing a code example from the book, but the engine swears at the error:
Assets\ReactiveTarget.cs(9,32): error CS0411: The type arguments for method 'Component.GetComponent()' cannot be inferred from the usage. Try specifying the type arguments explicitly.
As I understand it, the reason is that the example in the book is incorrect (since a similar error was previously, and was corrected by changing the syntax), but when changing the syntax from
WanderingAI behavior = GetComponent();
to
WanderingAI behavior = Component.GetComponent<WanderingAI>();
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WanderingAI : MonoBehaviour
{
public float speed = 3.0f;
public float obstacleRange = 5.0f;
private bool _alive;
void Start()
{
_alive = true;
}
void Update()
{
if (_alive)
{
transform.Translate(0, 0, speed * Time.deltaTime);
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
if (Physics.SphereCast(ray, 0.75f, out hit))
{
if (hit.distance < obstacleRange)
{
float angle = Random.Range(-100, 110);
transform.Rotate(0, angle, 0);
}
}
}
}
public void SetAlive(bool alive)
{
_alive = alive;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ReactiveTarget : MonoBehaviour
{
public void ReactToHit()
{
WanderingAI behavior = GetComponent(); // Именно на эту строку ругается Unity(
if (behavior != null)
{
behavior.SetAlive(false);
}
StartCoroutine(Die());
}
IEnumerator Die()
{
this.transform.Rotate(-75, 0, 0);
yield return new WaitForSeconds(1.5f);
Destroy(this.gameObject);
}
void Start()
{
}
void Update()
{
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question