Search Unity

Question Referencing another gameObject collision in a different gameObject script?

Discussion in 'Scripting' started by huntersimp2248, Mar 20, 2023.

  1. huntersimp2248

    huntersimp2248

    Joined:
    Mar 10, 2023
    Posts:
    1
    The title is a little confusing but basically I have a script on my bullet object that has a OnTriggerEnter2D function that I want to check to see if it happens on the script for my weapon, but I can't figure it out.

    The reason I want to do this is because when the bullet collides with a valid object it creates a teleport object (something that I haven't even started thinking about the code for), but I don't want to have multiple of these objects in the game at once, which is currently what's happening. I want a teleport object to be created if there isn't one already, and if there is, I want the newest one to stay and the oldest one to be destroyed. The problem is that I can't figure out how to track out many of these teleports I have in the game, and I think this is because I've been doing all of the code on the bullet script, which only gets played once when a bullet is fired and then is reset for the next bullet. So, I started trying to add this on my weapon script so that the bullet count is continuous, but I can't figure out how to detect collision with the bullet and be able to reference it in my weapon script.

    Sorry that was a lot of info, I'm terrible at explaining things. Lmk if more clarification is needed, and thank you! :D
     
  2. QuinnWinters

    QuinnWinters

    Joined:
    Dec 31, 2013
    Posts:
    494
    Make a reference to your weapon script in the bullet script and then modify a variable in it when the bullet collides with the correct collider.

    Code (CSharp):
    1.  public class BulletScript : MonoBehaviour {
    2.  
    3.     public WeaponScript weaponScript;
    4.  
    5.     void OnTriggerEnter (Collider collider) {
    6.  
    7.         if (collider.CompareTag ("Correct Collider")) {
    8.             weaponScript.teleportCount = 1;
    9.         }
    10.  
    11.     }
    12.  
    13. }
    14.  
    15. public class WeaponScript : MonoBehaviour {
    16.  
    17.     [HideInInspector] public int teleportCount = 0;
    18.  
    19.     void FireWeapon () {
    20.  
    21.         if (teleportCount == 0) {
    22.             //Fire a teleport bullet
    23.         }
    24.  
    25.     }
    26.  
    27. }