How to distinguish between different BoxCollider in the inspector Unity - c#

Let's say I have a gameobject "player" with 4 different BoxColliders2D
I have a wall script that's a component of the "wall" gameobject.
The wall script has 4 different public boxcolliders2D variables, but I can't seem to find a way to set each of them to their respective boxcollider2D in the player gameobject, in the inspector.

The wall script has 4 different public boxcolliders2D variables, but I
can't seem to find a way to set each of them to their respective
boxcollider2D in the player gameobject, in the inspector.
You can't do that from the Editor but you should be able to do this via code.
Initialize your 4 variables from code by using the GetComponents function which returns array of components attached to the GameObject. Notice the 's' at the end. That's different from the GetComponent function which returns just one GameObject.
public BoxCollider2D col1;
public BoxCollider2D col2;
public BoxCollider2D col3;
public BoxCollider2D col4;
void Awake()
{
BoxCollider2D[] colliders = GetComponents<BoxCollider2D>();
col1 = colliders[0];
col2 = colliders[1];
col3 = colliders[2];
col4 = colliders[3];
}
While the code version should work, do not attach multiple BoxCollider2D to one GameObject. What to do is create child GameObject for each extra collider you want then attach the BoxCollider2D component to it. This is the recommended way of using multiple colliders on one GameObject and that should solve your problem.
Below is a screenshot of what that should look like:
Now, you can drag each child Collider (BoxCollider2D 1, BoxCollider2D 2, BoxCollider2D 3) to the proper public variable name.

Related

How can I check multiple collider Triggers at once?

I have an aircraft in my game that is controlled by the player. I want it to get destroyed after it collides with something. The aircraft has many colliders on it, so im using an array. Heres my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AircraftDamage : MonoBehaviour
{
public Collider[] Colliders;
public GameObject Aircraft;
private void OnTriggerEnter(Colliders collision)
{
DestroyAircraft();
}
public void DestroyAircraft()
{
Destroy(Aircraft);
}
}
Im getting the obvious error here, type or namespace 'Colliders' could not be found. How can I check if any collider within my array gets triggered?
a better approach is to use OnCollisionEnter instead of OnTriggerEnter
You are missing the basics of Collision here. You don't need to reference the Colliders using an array.
Both OnCollisionEnter and OnTriggerEnter are called when the gameobject to which the script is attached collides with another collider. They return the collider with which it has collided.
So in your case its better to have a single collider on the parent gameobject rather than separate Colliders.
If you really want to have separate colliders for the airplane's body part then you need to add a collision checking script to each of the gameobject or you can add the collision checking script to your obstacles like building and have all your Airplane parts in a single tag.
Check out this guide on Unity collision

How to reference a GameObject's position in a prefab script in Unity

I'm just starting out with Unity and for my first game I'm trying to make these enemy cubes chase the player. The enemies are spawned at a random position and I'm trying to make them move towards the position of the player cube. But when I try to reference the player's Transform, it won't let me drag it on top, any fixes?
using UnityEngine;
public class enemyFollow : MonoBehaviour {
public Transform player;
public Rigidbody rb;
public float movementForce;
// Update is called once per frame
void FixedUpdate()
{
if (player.position.x > transform.position.x){
rb.AddForce(movementForce * Time.deltaTime,0,0);
}
if (player.position.x < transform.position.x){
rb.AddForce(-movementForce * Time.deltaTime,0,0);
}
if (player.position.z > transform.position.z){
rb.AddForce(0,0,movementForce * Time.deltaTime);
}
if (player.position.z < transform.position.z){
rb.AddForce(0,0,-movementForce * Time.deltaTime);
}
}
}
Unity won't let me drag the player from the gameobjects window onto the script on the prefab. The error says "the variable player of enemyFollow has not been assigned"
It won't let me assign Player.
You can add this in a void Start() method:
player = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
If I'm understanding correctly, you're trying to assign the player to the enemy in the prefab configuration. That won't work because the prefab isn't in the scene. Since the prefab could be instantiate in any scene, you can't reference scene objects. You need to do it during playtime, unless all the enemies are already in the scene when you're setting it up (in which case you'd need to do it to an instantiated enemy and then copy paste it).
You can use FindGameObjectWithTag() as in Jeff's answer, but make sure to assign a "Player" tag to the player GameObject or prefab.
Another method which I'd recommend would be to have whatever is instantiating the enemies assign their target, that way you don't need to search for a tag with a string you could mistype, and you can just change the reference in one place when you need to change something.

How to teleport player to different scene via trigger?

I have used the most traditional method of doing this but it doesn't work. No response is initiated.
I've attached a rigidbody2d collider (with 0.0001 mass and no drag or gravity) to my player sprite and a box collider 2d with is trigger checked.
Sidenote: Outdoor1" is the name of the scene I want to teleport my player to.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class TeleportToScene : MonoBehaviour
{
[SerializeField] private string newScene;
void OnTriggerStay2D(Collider2D other)
{
if (other.CompareTag ("Player"))
{
SceneManager.LoadScene("Outdoor1");
I expect it to go over the box collider and change scenes but nothing happens. No error messages either.
to make OnTriggerStay2D you need to have an collider 2D set to trigger on the object who as the script TeleportToScene and a Rigidbody2D
So you scene will be, 2 object:
1.Player with
- Deplacement
- Collider2D(not trigger)
- Tag "Player"
2.Teleporter with
- TeleportToScene.cs
- Collider2D (trigger)
- Rigidbody2D (kinematic)
Hope that help !

How come the Collider falls from the GameObject when a RigidBody is added?

I could really need some help with my GameObjects.
I am working on a game in which I want a pick-up Item to create a Physics Force explosion to blow away the enemies. I made a simple Bomb-Object to test this idea. I added a straightforward code, using a loop to collect all the colliders within its radius, to then addForce to these colliders. Now the code is working properly, but not all my GameObjects are reacting properly.
I looked into why this is, and I noticed that my Collider keeps falling away from the GameObject as soon as I add a RigidBody component to the object. The RigidBody is needed for the AddForce impact. When I remove the rb, the collider stays in place, but the object does not react to the Physics Force.
I added some images to illustrate what I mean:
Image of the Collider of the leaf sinking away..
Example image of objects which DO react to the AddForce.
I already tried to:
Copy/Paste all component settings from the reacting Cube and stone
Gameobjects to the Leaf Gameobject while disabling all other code
such as the c# scripts. The Collider & RB do not fall through the
floor but when Physics Force hits the Collider is blown away while
the GameObject keeps its position.
Try different GameObjects/Collider types.
Removed the water.
Play with amount of force/radius of the bomb.
Edited 'Tag' and 'Layerstyle' of GameObject.
The 'Explosion Code' is added below, however, I don't think the problem is in the code. I added the code to the Main Camera of my scene, and added a simple sphere as the 'bomb' GameObject.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Explosion : MonoBehaviour
{
public GameObject bomb; //set the position of the explosion
public float power = 10.0f;
public float radius = 10.0f;
public float upForce = 0.0f;
private void FixedUpdate()
{
if (Input.GetKeyDown("space"))
{
print("space key was pressed");
Invoke("Detonate", 1);
}
}
void Detonate()
{
Vector3 explosionPosition = bomb.transform.position; //set the position of our explosion to the position of the bomb.
Collider[] colliders = Physics.OverlapSphere(explosionPosition, radius); //collects all colliders within the radius.
foreach (Collider hit in colliders) { //for each individual collider the following code is ran.
Rigidbody rb = hit.GetComponent<Rigidbody>(); //declare'rb' rigidbody. Get rb component from each collider
if (rb != null)
{
print("BOOM!");
rb.AddExplosionForce(power, explosionPosition, radius, upForce, ForceMode.Impulse); //add force to each collider
}
}
}
}
How do I make the Rigidbody, Collider and GameObject of the leaf hold onto each other like the standard 3D object 'cube', so that I can make these blow away with the Physics Force just like the other models?
Thank you for your time, I have been trying things and looking around on the Internet for hours now but can't seem to find any solution.
What happens if you add the rigidbody in stop mode and press play? Does it move away in a similar manner? This may, and is expected to happen, if your colliders intersect with each other. As soon as you add a rigidbody, they find themselves trapped in a serious collision.
If you don't want to modify the scene, you can fiddle with the collision matrix in project settings / physics

Unable to add force to instantiated object

Currently instantiating an object (a prefab) at run time via a button click. The object instantiates each time I click the button but it doesn't move even though I have added force to it.
Checked similar issues where its a mismatch of casting between GameObject and Rigidbody2D but this isn't the issue in my case. Tried switching between transform right and forward multiplied by a large number in case the value was too small for a change which doesn't make a difference either. Any help is appreciated. Thank you.
Following script is on the Player object. The prefab is instantiated from the object 'tip' which is a child object on the Player object. Rigidbody2D is set to Kinematic for bullet.
public Transform tip;
public Rigidbody2D bullet;
if (Input.GetButtonDown("Fire1")) {
Rigidbody2D clone;
clone = Instantiate(bullet, tip.position, Quaternion.identity) as Rigidbody2D;
clone.AddForce(clone.transform.right * 5000000);
}
Rigidbody2D is set to Kinematic for bullet.
This is the mistake: the physics engine never moves Kinematic objects, change the bullet rigidbody body type to Dynamic, and the force you apply with AddForce will move the bullet.

Categories

Resources