How do I make multiple of the same colliders for a gameobject (2D),
Basically, I'm trying to make an enemy that uses two box colliders.
What I've done is made a child object to the enemy that has it's own script and it's own box collider, and it worked out well. The problem with this was that when I tried to make a second enemy using that enemy prefab, both enemies seemed to be using the same instance of the child script (was broken). This is what my code looks like:
Enemy:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour
{
[SerializeField] float enemyRunSpeed = 5f;
Rigidbody2D enemyRigidBody;
bool flipIt;
// Start is called before the first frame update
void Start()
{
enemyRigidBody = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
flipIt = false;
flipIt = FindObjectOfType<Parascope>().FlipSprite();
if (flipIt)
{
FlipSprite();
FindObjectOfType<Parascope>().SetCollison(false);
}
if (IsFacingLeft())
{
enemyRigidBody.velocity = new Vector2(-enemyRunSpeed, enemyRigidBody.velocity.y);
} else
{
enemyRigidBody.velocity = new Vector2(enemyRunSpeed, enemyRigidBody.velocity.y);
}
}
private void OnTriggerExit2D(Collider2D collision)
{
}
private void FlipSprite()
{
transform.localScale = new Vector2(Mathf.Sign(enemyRigidBody.velocity.x), enemyRigidBody.transform.localScale.y);
}
private bool IsFacingLeft()
{
return transform.localScale.x > 0;
}
}
Enemy Child Box Collider
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Parascope : MonoBehaviour
{
BoxCollider2D parascopeCollider;
bool collisionIsTrue = false;
// Start is called before the first frame update
void Start()
{
parascopeCollider = GetComponent<BoxCollider2D>();
}
// Update is called once per frame
void Update()
{
print(collisionIsTrue);
}
public void SetCollison(bool value)
{
collisionIsTrue = value;
}
private void OnTriggerExit2D(Collider2D collision)
{
collision = parascopeCollider;
collisionIsTrue = true;
FlipSprite();
}
public bool FlipSprite()
{
return collisionIsTrue;
}
}
I'm very new to unity, and I'm using unity 2021 and 2d. Please help me :)
,
Your answer

Follow this Question
Related Questions
Edge collider BoxCast issue 0 Answers
Adding Rigidbody2d to gameobject removes it from game 0 Answers
GameObject keeps colliding for sometime after being destroyed 1 Answer
2DBoxCollider too small for OnMouseDown? 0 Answers
Simple Run Game 2d Death 1 Answer