i have two simple 3d cube objects a,b. so my task is to randomly disable box collider one of the object every time game start.
my initial thought is randomly generate Boolean and if it is false then disable the box collider.
You can add you cube's to array and use Random.Range(0, yourArray.Length) to get index of the cube which should be deactivated. In your case it will be some overhead but this solution will be work for different cube`s count in the future.
In code it will looks like:
// You can serialize this array and add cubes from Inspector in Editor
// or add script with this code to the parent gameobject
// and use GetComponentsInChildren<BoxCollider>() to get all colliders
var cubes = new BoxCollider[2] {firstCube, secondCube};
var cubeToDeactivationIndex = Random.Range(0, cubes.Length);
cubes[cubeToDeactivationIndex].enabled = false;
About your second question. If I understand correctly, implementation will be next:
using System;
using UnityEngine;
using UnityEngine.Assertions;
using Random = UnityEngine.Random;
// Interface need to provide limited API
// without open references to gameobject and transform of the object
public interface ICollidable
{
event Action<ICollidable> OnCollided;
int HierarchyIndex { get; }
void DisableCollider();
}
// This component you should add to the object which will collide with player
public class CollidableObject : MonoBehaviour, ICollidable
{
[SerializeField]
private Collider _objectCollider;
public event Action<ICollidable> OnCollided;
public int HierarchyIndex => transform.GetSiblingIndex();
private void Start()
{
Assert.IsNotNull(_objectCollider);
}
//Here you can use your own logic how to detect collision
//I written it as example
private void OnCollisionEnter(Collision collision)
{
if (collision.transform.CompareTag("Player")) {
OnCollided?.Invoke(this);
}
}
public void DisableCollider()
{
_objectCollider.enabled = false;
}
}
// This component should be on the parent gameobject for your `
// collidable objects. As alternative you can serialize array
// and add all collidable objects from the Inspector but in that
// case signature of the array should be CollidableObject[]
// because Unity can`t serialize interfaces
public class RamdomizedActivitySwitcher : MonoBehaviour
{
private ICollidable[] _collidableObjects;
private void Awake()
{
_collidableObjects = GetComponentsInChildren<ICollidable>(true);
foreach (var collidable in _collidableObjects)
{
collidable.OnCollided += DisableObjectWhenMatch;
}
}
private void DisableObjectWhenMatch(ICollidable collidedObject)
{
var randomIndex = Random.Range(0, _collidableObjects.Length);
if (randomIndex == collidedObject.HierarchyIndex) {
collidedObject.DisableCollider();
}
}
}
}
Related
I am doing a 2d game and I want my player to be able to change bullets when he collides with an object(power) and destroy that object. I have a script and I was thinking that I need to implement 2 variables prefab ON/Off but now thinking much more I want to change with the help of a tag ( My player has in his script a public Rigidbody2D bullet) and this function
void Fire()
{
if (photonView.IsMine)
{
var firedBullet = Instantiate(bullet, barrel.position, barrel.rotation);
firedBullet.AddForce(barrel.up * bulletSpeed);
}
}
this is the script that I was working on for switching bullets but I think it will not work to change a bullet that I add in the inspector for the Character script , to disable from this script and add other bullet . How I can make it by tag?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WeaponSwitching : MonoBehaviour
{
[SerializeField] private GameObject pickupEffect;
public GameObject[] DisablePrefab;
public GameObject[] EnablePrefab;
public int selectBullet = 0;
// Start is called before the first frame update
// Update is called once per frame
public void Bullet(Character bullet)
{
var effect = Instantiate(pickupEffect, transform.position, transform.rotation);
foreach (GameObject disable in DisablePrefab)
{
disable.SetActive(false);
}
foreach (GameObject enable in EnablePrefab)
{
enable.SetActive(true);
}
Destroy(gameObject);
Destroy(effect, 3.0f);
}
}
and I try this think with a BulletSwitch script to call the function from Weapon Switching script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletSwitch : MonoBehaviour
{
[SerializeField] private Character bullet;
// Start is called before the first frame update
private void Awake()
{
if (!bullet) bullet = GetComponent<Character>();
}
private void OnTriggerEnter2D(Collider2D other)
{
// or whatever tag your powerups have
if (!other.CompareTag("Bullet"))
{
Debug.LogWarning($"Registered a collision but with wrong tag: {other.tag}", this);
return;
}
var Bullet = other.GetComponent<WeaponSwitching>();
if (!Bullet)
{
Debug.LogError($"Object {other.name} is tagged PowerUp but has no PowerUp component attached", this);
return;
}
Debug.Log("Found powerup, pick it up!", this);
Bullet.Bullet(bullet);
}
}
inspector character
after my player collides with an object the bullets disappear.
You could make an array of prefabs and change to the correct bullet type when you hit a powerup by setting a CurrentBulletType variable to one of the types from the array. So when you hit powerup X, change bullet type to one of the types from the array.
public GameObject currentPrefab;
public GameObject[] bulletPrefabs;
private void OnTriggerEnter2D(Collider2D other)
{
string tagString = other.tag;
bool foundObject = true;
switch (tagString)
{
case "standard bullet":
currentPrefab = bulletPrefabs[0];
break;
case "fancy bullet":
currentPrefab = bulletPrefabs[1];
break;
case "even fancier bullet":
currentPrefab = bulletPrefabs[2];
break;
default:
foundObject = false;
break;
}
if (foundObject) other.gameObject.SetActive(false);
}
You can instead use a dictionary to directly reference the correct prefab by string name (tag) to make it easy to add more bullet types.
//dictionairy to reference bullet types quickly
public Dictionary<string, BulletTypes> bulletLibrary = new Dictionary<string, BulletTypes>();
//set these in the inspector
public BulletTypes[] bulletTypes;
[System.Serializable]
public struct BulletTypes
{
public string bulletName;
public GameObject prefab;
//public int bulletPower; //more data if you wish
}
private void Start()
{
//fill the dictionary based on the filled bullet type array in inspector
for (int i = 0; i < bulletTypes.Length; i++)
{
if (bulletTypes[i].bulletName != "")
bulletLibrary.Add(bulletTypes[i].bulletName, bulletTypes[i]);
else
print("bullet added, but name empty");
}
}
private void OnTriggerEnter2D(Collider2D other)
{
string tagString = other.tag;
//if the collided tag is in the dictionary, we can reference the bullet type from that dictionairy
if (bulletLibrary.ContainsKey(tagString))
{
print("spawn: " + bulletLibrary[tagString].bulletName);
print("prefab: " + bulletLibrary[tagString].prefab);
//all the data you need is in: bulletLibrary[tagString];
//Bullet.Bullet(bulletLibrary[tagString]);
other.gameObject.SetActive(false);
}
}
Sidenote: If you spawn a lot of bullets, you can use pooling. SimplePool is nice and easy for this. Instead of calling: instantiate and destroy, you call: SimplePool.Spawn() and SimplePool.DeSpawn().
If you have any more questions on this feel free to ask ;)
I need help with my project in unity
I want to stop each object by clicking on it.
What I did so far:
all my objects rotate but when I click anywhere they all stop, I need them to stop only if I click on each one.
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EarthScript : MonoBehaviour
{
public bool rotateObject = true;
public GameObject MyCenter;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
if(rotateObject == true)
{
rotateObject = false;
}
else
{
rotateObject = true;
}
}
if(rotateObject == true)
{
Vector3 axisofRotation = new Vector3(0,1,0);
transform.RotateAround(MyCenter.transform.position,axisofRotation, 30*Time.deltaTime);
transform.Rotate(0,Time.deltaTime*30,0,Space.Self);
}
}
}
Theres two good ways to achieve this. Both ways require you to have a collider attatched to your object.
One is to raycast from the camera, through the cursor, into the scene, to check which object is currently under the cursor.
The second way is using unity's EventSystem. You will need to attach a PhysicsRaycaster on your camera, but then you get callbacks from the event system which simplifies detection (it is handled by Unity so there is less to write)
using UnityEngine;
using UnityEngine.EventSystems;
public class myClass: MonoBehaviour, IPointerClickHandler
{
public GameObject MyCenter;
public void OnPointerClick (PointerEventData e)
{
rotateObject=!rotateObject;
}
void Update()
{
if(rotateObject == true)
{
Vector3 axisofRotation = new Vector3(0,1,0);
transform.RotateAround(MyCenter.transform.position,axisofRotation, 30*Time.deltaTime);
transform.Rotate(0,Time.deltaTime*30,0,Space.Self);
}
}
We have got various controllers developed for moving gameobjects. I have used magnetometer/gyro sensor to move game object using MUVSlide through following code:
using UnityEngine;
using ForestIndieGames.Muvslide;
public class Connection : MonoBehaviour {
private static bool created = false;
private bool newInputAvailable;
private MuvslideConnection muvslideConn;
private void Awake()
{
if (!created)
{
DontDestroyOnLoad(this.gameObject);
created = true;
muvslideConn = new MuvslideConnection();
}
}
private void OnApplicationQuit()
{
if (muvslideConn != null)
muvslideConn.Close();
}
private void Update()
{
if (muvslideConn.GetInputManager().IsNewMotionAvailable())
newInputAvailable = true;
}
public bool IsNewInputAvailable()
{
bool result = newInputAvailable;
newInputAvailable = false;
return result;
}
public Vector3 GetAngles()
{
float[] angles = muvslideConn.GetInputManager().GetOrientationDegrees();
return new Vector3(angles[0], angles[1], angles[2]);
}
}
What I am trying to achieve is to move a gameobject by a real light spot on the wall. The spot is on the wall and fed through a camera. When the spot moves I want game object to follow exactly. The light spot can be a specific color or IR or UV etc.
Any leads please
I am experiencing the strangest issue
I have a ray cast and when it touches a certain layer it calls my function which does a small animation.
The problem is, this only works on a single object, I have tried duplicating, copying the prefab, dragging prefab to the scene, it doesn't work.
Now I have this code below, and as you can see I have this line which allows me to access the script on public PlatformFall platfall; so I can call platfall.startFall();
Something I've noticed, If I drag a single item from the hierarchy to the public PlatFall in Inspector then that SINGLE object works as it should. ( in that it animates when startFall is called). HOWEVER, if I drag the prefab from my project to the inspector then they do not work. (Even if debug log shows that the method is called animation does not occur).
public class CharacterController2D : MonoBehaviour {
//JummpRay Cast
public PlatformFall platfall;
// LayerMask to determine what is considered ground for the player
public LayerMask whatIsGround;
public LayerMask WhatIsFallingPlatform;
// Transform just below feet for checking if player is grounded
public Transform groundCheck;
/*....
...*/
Update(){
// Ray Casting to Fallingplatform
isFallingPlatform = Physics2D.Linecast(_transform.position, groundCheck.position, WhatIsFallingPlatform);
if (isFallingPlatform)
{
Debug.Log("Here");
platfall.startFall();
}
Debug.Log(isFallingPlatform);
}
}
Platform Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlatformFall : MonoBehaviour
{
public float fallDelay = 0.5f;
Animator anim;
Rigidbody2D rb2d;
void Awake()
{
Debug.Log("Awake Called");
anim = GetComponent<Animator>();
rb2d = GetComponent<Rigidbody2D>();
}
private void Start()
{
Debug.Log("Start Called");
}
//void OnCollisionEnter2D(Collision2D other)
//{
// Debug.Log(other.gameObject.tag);
// GameObject childObject = other.collider.gameObject;
// Debug.Log(childObject);
// if (other.gameObject.CompareTag("Feet"))
// {
// anim.SetTrigger("PlatformShake");
// Invoke("Fall", fallDelay);
// destroy the Log
// DestroyObject(this.gameObject, 4);
// }
//}
public void startFall()
{
anim.SetTrigger("PlatformShake");
Invoke("Fall", fallDelay);
Debug.Log("Fall Invoked");
// destroy the Log
// DestroyObject(this.gameObject, 4);
}
void Fall()
{
rb2d.isKinematic = false;
rb2d.mass = 15;
}
}
I understood from your post that you are always calling PlatformFall instance assigned from inspector. I think this changes will solve your problem.
public class CharacterController2D : MonoBehaviour {
private PlatformFall platfall;
private RaycastHit2D isFallingPlatform;
void FixedUpdate(){
isFallingPlatform = Physics2D.Linecast(_transform.position, groundCheck.position, WhatIsFallingPlatform);
if (isFallingPlatform)
{
Debug.Log("Here");
platfall = isFallingPlatform.transform.GetComponent<PlatformFall>();
platfall.startFall();
}
}
}
By the way, i assume that you put prefab to proper position to cast. And one more thing, you should make physics operations ,which affect your rigidbody, in FixedUpdate.
Imagine I have 2 gameobjects, red plate and apple.
When game start(this is crucial), apple already on red plate(2 gameobjects already in contact). so if I move red plate, the apple is "parented" to red plate and follow the transform.
How can I do that in Unity3D? I look at the code Trigger and Collision, both of them need to at least a stage that 1 moving gameobject to collide the other, which I don't have that.
Any idea how to deal with this?
I found the solution: Bounds.Intersect
As in:
var bounds1 = gameObject1.renderer.bounds;
var bounds2 = gameObject2.renderer.bounds;
if (bounds1.Intersects(bounds2))
{
// do something
}
So with this, my problem solved.
Probably the simplest implementation is to use OnTriggerEnter and OnTriggerExit to toggle the parenting of one object's transform to another, so that all children of the parent will accept the transform operations performed on the parent.
Example:
using UnityEngine;
[RequireComponent(typeof(BoxCollider))]
[RequireComponent(typeof(Rigidbody))]
public class
PlateCollider : MonoBehaviour
{
private void
Awake()
{
rigidbody.isKinematic = false;
rigidbody.useGravity = false;
collider.isTrigger = false;
}
}
And
using UnityEngine;
[RequireComponent(typeof(SphereCollider))]
[RequireComponent(typeof(Rigidbody))]
public class
AppleCollider : MonoBehaviour
{
private void
Awake()
{
rigidbody.isKinematic = false;
rigidbody.useGravity = false;
collider.isTrigger = false;
}
private void
OnCollisionEnter(Collision collision)
{
PlateCollider tryGetPlate = collision.gameObject.GetComponent<PlateCollider>();
if (tryGetPlate != null)
{
transform.parent = tryGetPlate.gameObject.transform;
}
}
private void
OnCollisionExit(Collision collision)
{
PlateCollider tryGetPlate = collision.gameObject.GetComponent<PlateCollider>();
if (tryGetPlate != null)
{
transform.parent = null;
}
}
}
There's many other ways you can use to compare the two objects. In this example I try to get the component on a colliding gameobject and check if the component reference exists. Collision tags might be a better option for you, it might not.