How can I add the game object from above (Roed Knap, Hand etc.) into the script given below (at the picture)?
This is an example project. I can't figure out to reference GameObject's and Colliders into a Script.
What I want to do is very simple.
Make a GameObject with a Collider, and trigger something when collision happens.
So What I have is basically a GameObject Cube that has a Collider sphere added and for this isTrigger is selected. I want this trigger when entering, modify the text. Can you help me with initializing, referencing and other stuffs necessary, see below code. This is the code I work with.
using UnityEngine;
using System.Collections;
public class NewBehaviourScript : MonoBehaviour {
GameObject Cube;
GUIText Text;
Collider collision;
// Use this for initialization
void Start () {
collision = Cube.GetComponent<Collider> ();
Text = GetComponent ("GuiText") as GUIText;
}
// Update is called once per frame
void Update () {
}
void onTriggerEnter(){
Text.text = "Won"
}
}
Unity uses C# syntax for all of MonoBehaviour and engine namings. That is, a method starts with cap letter:
void OnTriggerEnter(Collider col){}
Related
In my Unity game I have some moving objects. There are some collectables ( triggers ) and whenever a moving object enters its trigger the collectable should
Replace itself with a moving object
Destroy itself
Unfortunately the current moving object collides with the new spawned moving object so it will be out of position ( very little ). I would like to avoid that, so one piece connects smoothly to the other one.
For reproduction purposes:
Moving
Create a cube GameObject
Add a Rigidbody component but disable the usage of gravity
Attach the following script to it
.
public class MoveForwardBehaviour : MonoBehaviour
{
private void FixedUpdate()
{
GetComponent<Rigidbody>().velocity = Vector3.forward; // just for testing purposes
}
}
Make this GameObject a prefab
Collectable
Create a cube GameObject
Add a Rigidbody component but disable the usage of gravity
Enable the collider trigger and modify the following values
Attach the following script to it
.
public class Collectable : MonoBehaviour
{
[SerializeField] private GameObject movingPrefab;
private void OnTriggerEnter(Collider other)
{
GetComponent<Collider>().enabled = false;
Instantiate(movingPrefab, transform.position, transform.rotation);
Destroy(gameObject);
}
}
Assign the moving prefab to the script
Make this GameObject a prefab
Now setup a sample scene like so
and start the game. After creating a new moving prefab you can see that the initial moving prefab is not in position anymore
I think this is because of the collision with the new instantiated prefab. Do you have any suggestions how to avoid this?
i am bloody beginner with Unity and i am currently working on a 2D Brawler. The movement works perfectly but my colliders don't do what they should... I want to detect if two GameObjects Collide (Spear and Player2) and if the collide Player2s healthPoints should decrease by Spears AttackDamage.
The names of the GameObjects are also their tags. The Spears Prefab has following configuration: SpriteRendered(Material Sprites-Default), BoxCollider2D(Material None Physics Material 2D, IsTrigger(not activated), UsedByEffector(also not activated) Rigidbody2D(Kinematic, None Material, Simulated(Activated), KinematicContacts(activated), Standard configs for the rest))
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpearCtr : MonoBehaviour {
public Vector2 speed;
public float delay;
Rigidbody2D rb;
void Start ()
{
rb = GetComponent<Rigidbody2D>();
rb.velocity = speed;
Destroy(gameObject, delay);
}
void Update ()
{
rb.velocity = speed;
}
}
The Players Configurations
The Spears Configurations
This was the code i have tried before
OnCollision2D(Collision2D target);
{
if (target.gameObject.tag == "Spear")
{
hp = -1;
if (hp <= 0)
{
alive = false;
}
}
}
I hope someone can tell me how to get this working
Thanks for all the answers
(BTW sorry for my bad english I am austrian)
enter image description here
enter image description here
Reasons why OnCollisionEnter() does not work:
Collison:
1.Rigidbody or Rigidbody2D is not attached.
At-least, one of the two GameObjects must have Rigidbody attached to it if it is a 3D GameObject. Rigidbody2D should be attached if it is a 2D GameObject/2D Collider.
2.Incorrect Spelling
You failed to spell it right. Its spelling is also case sensitive.
The correct Spellings:
For 3D MeshRenderer/Collider:
OnCollisionEnter
OnCollisionStay
OnCollisionExit
For 2D SpriteRenderer/Collider2D:
OnCollisionEnter2D
OnCollisionStay2D
OnCollisionExit2D
3.Collider has IsTrigger checked. Uncheck this for the OnCollisionXXX functions to be called.
4.The script is not attached to any of the Colliding GameObjects. Attach the script to the GameObject.
5.You provided the wrong parameter to the callback functions.
For 3D MeshRenderer/Collider:
The parameter is Collision not Collider.
It is:
void OnCollisionEnter(Collision collision) {}
not
void OnCollisionEnter(Collider collision) {}
For 2D SpriteRenderer/Collider2D:
6.Both Rigidbody that collides has a isKinematic enabled. The callback function will not be called in this case.
This is the complete collison table:
This is semi complicated of a question but I'll do my best to explain it:
I am making this mobile game in which you have to shoot four cubes. I'm trying to make it so when the cubes are shot by a bullet, they're destroyed and a UI text says 1/4, to 4/4 whenever a cube is shot. But it's being really weird and only counts to 1/4 even when all four cubes are shot and destroyed. I put these two scripts on the bullets (I made two separate scripts to see if that would do anything, it didn't)
And to give a better idea of what I'm talking about, here's a screenshot of the game itself.
I've been using Unity for about 6 days, so I apologize for anything I say that's noob-ish.
EDIT
So I combined the two scripts onto an empty gameobject and here's the new script:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class GameManagerScript : MonoBehaviour {
public GameObject cubes;
public Text countText;
public int cubeCount;
public Transform target;
// Use this for initialization
void Start () {
}
void OnTriggerEnter(Collider other)
{
cubes = other.gameObject;
}
// Update is called once per frame
void Update () {
cubes.transform.position = Vector3.MoveTowards(transform.position, target.position, 1f * Time.deltaTime);
if (cubes.gameObject.tag == "BULLET")
{
cubeCount = cubeCount + 1;
countText.text = cubeCount + "/4";
cubes.SetActive(false);
}
}
}
ANOTHER EDIT
I tried everything, so is there a way to detect when all the children in a parent on the Hierarchy are destroyed? Instead of counting up? This can give a better idea:
So I want to be able to detect when Cube, Cube1, Cube2, and Cube3 have all been destroyed.
The answer is pretty simple: Since every individual bullet has that script, each bullet has its own score.
For something like a score you want a single spot to store it, e.g. a script on an empty gameobject that serves as game controller. Just access that in the collision and increase the score (maybe have a look on singletons here).
You can combine those two scripts and actually it might be better to not have this on the bullet, but on the target because there are probably less of them which will save you some performance. (And it does more sense from a logical point of view.)
Edit:
I assume you create the bullets using Instantiate with a prefab. A prefab (= blueprint) is not actually in the game (only objects that are in the scene/hierarchy are in the game). Every use of Instantiate will create a new instance of that prefab with it's own version of components. A singleton is a thing that can only exist once, but also and that is why I mention it here, you can access it without something like Find. It is some sort of static. And an empty gameobject is just an object without visuals. You can easily create one in unity (rightclick > create empty). They are typically used as container and scriptholders.
Edit:
What you want is:
An empty gameobject with a script which holds the score.
A script that detects the collision using OnTriggerEnter and this script will either be on the bullets or on the targets.
Now, this is just a very quick example and can be optimized, but I hope this will give you an idea.
The script for the score, to be placed on an empty gameobject:
public class ScoreManager : MonoBehaviour
{
public Text scoreText; // the text object that displays the score, populate e.g. via inspector
private int score;
public void IncrementScore()
{
score++;
scoreText.text = score.ToString();
}
}
The collision script as bullet version:
public class Bullet : MonoBehaviour
{
private ScoreManager scoreManager;
private void Start()
{
scoreManager = GameObject.FindWithTag("GameManager").GetComponent<ScoreManager>(); // give the score manager empty gameobject that tag
}
private void OnTriggerEnter(Collider other)
{
if(other.CompareTag("Target") == true)
{
// update score
scoreManager.IncrementScore();
// handle target, in this example it's just destroyed
Destroy(other.gameObject);
}
}
}
I have two game object.
Both gameobject positions are different...
I attached same animation clip to both gameobject.
In one game object I am don't want any change in animation clip.
I just want to use same animation clip on different gameobject but animation timing is different
& In other Gameobject I am just want to play animation at 0.30 s but I not knowing how set position of this gameobject in script.
I am assign below script to second game object.
using UnityEngine;
using System.Collections;
public class ani3 : MonoBehaviour {
void Start () {
animation ["#cube"].time = 0.30f;
//how to set position of gameobjet
}
void Update () {
gameObject.animation.Play("#cube");
}
}
you can use a empty game object and nest one of the game object as child and change the position of the empty game object ,it is work for me.
using UnityEngine;
using System.Collections;
public class chicken_for : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void FixedUpdate () {
if (collision.gameObject.Quad == collisionObject){
Application.LoadLevel("SciFi Level");
}
}
}
I am attempting to when A person touches a quad, he goes to this sci-fi fortress. It however says the name 'collision' does not exist in the current context.
You're referencing a variable (collision) that doesn't exist. You've got a variable collisionObject that doesn't exist, too.
collision is typically the name of the argument to the OnCollisionEnter method. Your code should probably be inside this method instead of FixedUpdate. I'm guessing that you've copied code from a tutorial somewhere but put it in the wrong method.
collisionObject on the other hand is harder to guess, but I expect that if your script is intended to be a component on the player object, then collisionObject should be your quad; if the script is on the quad then collisionObject should be the player.
Either way, you need to declare that variable - probably as a public field so that you can populate it from the inspector.
Add a new function and make sure the player is tagged as player in the inspector. You also need to make sure that there is a collider on the quad that the player touches and a rigidbody component on the player.
using UnityEngine;
using System.Collections;
public class chicken_for : MonoBehaviour {
//This function will handle the collision on your object
void OnCollisionEnter (Collider col){
if(col.gameobject.tag == "Player"){ //if colliding object if tagged player
Application.LoadLevel("SciFi Level"); //load the sci-fi level
}
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
This should get you roughly where you want to be!