Answer the question
In order to leave comments, you need to log in
How to create a variable that can be equated to any script via GetComponent?
Good day!
I'm making a scrolling shooter with Unity. Different enemies have different scripts, but they use the same bullet prefab. The bullet must take a vector variable from the enemy script, but when writing a script, a problem arises: for different enemies, you have to write a separate script variable. Moreover, when it appears, the variable is equated to the script via GetComponent in the try-catch block, which is why the bullet often simply fails to get the vector and it remains hanging in place. How can I solve my problem?
Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyBullet : MonoBehaviour
{
[SerializeField] Rigidbody2D rb;
[SerializeField] float speed;
Vector2 dir;
bool is_changed = false;
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Player")) { Destroy(this.gameObject); }
if (collision != null)
{
if (!is_changed)
{
try
{
try
{
dir = collision.GetComponent<EnemyCannon>().direction;
}
catch { }
try
{
dir = collision.GetComponent<CrossEnemyCannon>().direction;
}
catch { }
is_changed = true;
}
catch { }
}
}
}
private void FixedUpdate()
{
rb.velocity = dir.normalized * speed;
}
}
Answer the question
In order to leave comments, you need to log in
And if you control a bullet from an enemy script? Are you considering this option? For example:
public Rigidbody shoot;
void fire1 ()
{
Rigidbody rocketClone = (Rigidbody) Instantiate(shoot, transform.position, transform.rotation);
rocketClone.velocity = cannon.transform.forward *100f;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question