V
V
Void592021-11-02 14:28:03
C++ / C#
Void59, 2021-11-02 14:28:03

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

2 answer(s)
F
freeExec, 2021-11-02
@freeExec

https://metanit.com/sharp/tutorial/3.7.php

C
Crebor, 2021-11-02
@Crebor

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 question

Ask a Question

731 491 924 answers to any question