So I'm working on a Pong project as a learning tool to help me get used to Unity as a development studio. What I want to do is create a Particle System every time the ball hits either paddle. So I put a particle system as a child under each paddle, and made it so it called that particle system every time the ball made contact with the paddle in C#. It doesn't work, and I want to make it so it calls the particle system at the point of impact between the ball and the paddle. Here's the code I currently have:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExplosionScript : MonoBehaviour {
public GameObject explosionParticle;
void OnCollisionEnter2D (Collision2D coll) {
if (coll.collider.CompareTag ("Player")) {
Explode ();
}
}
void Explode () {
Instantiate (explosionParticle, Vector3.zero, Quaternion.identity);
}
}
This code is attached to the ball GameObject.
Try
explosionParticle.Play(); after instantiating.
typically I create a separate ParticleSystem gameobject and not a child so I can prefab or modify it. Then I declare
public ParticleSystem explosion; then attach the ParticleSystem gameobject to the ball explosion property.
In code I would do just this
Instantiate(explosion, transform.position, Quaternion.identity);
explosion.Play();
Related
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
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.
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
I am trying to make a replica of Asteroids in Unity. The problem is that my bullets are not triggering the OnTriggerEnter2D method on the asteroids. The asteroids have the following script attached:
using UnityEngine;
using System.Collections;
public class Asteroid : MonoBehaviour {
void Start () {
print ("class initiated");
}
void onTriggerEnter2D (Collider2D collider) {
Debug.Log (collider);
}
}
The bullet GameObject has Is Kinematic and Is Trigger enabled, and has Rigidbody 2D and Box Collider 2D attached. The asteroid GameObject has Rigidbody 2D and Circle Collider 2D, and Is Kinematic and Is Trigger is unchecked.
The problem is the Spelling. The o in onTriggerEnter2D should be capitalized. Simple mistake like this one can ruin your day. I didn't even notice it until I ran your code.
void OnTriggerEnter2D(Collider2D collider)
{
Debug.Log(collider);
}
Next time if you are not sure about the spelling of the Unity callback function, right click in Visual Studio then click Implement MonoBehaviours search for the function you want, select it and click OK. Visual Studio will add that function for you.
So, i want to use camera.ViewportToWorldPoint() to show the bottom center bounds of my screen. So, I created a script, add that component to my object that need it.
using UnityEngine;
using System.Collections;
public class PathMovement : MonoBehaviour {
public Camera cam;
private Vector3 bound;
void Awake () {
cam = GetComponent<Camera> ();
}
void Start(){
bound = cam.ViewportToWorldPoint (new Vector3 (0f, 0.5f));
Debug.Log (bound);
}
}
and then, I attach the MainCamera via the GUI
And then, when I run it, there's still an error says :
MissingComponentException: There is no 'Camera' attached to the "RiverPath" game object, but a >script is trying to access it.
You probably need to add a Camera to the game object "RiverPath". Or your script needs to check if >the component is attached before using it.
UnityEngine.Camera.ViewportToWorldPoint (Vector3 position) (at C:/buildslave/unity/build/artifacts/generated/common/runtime/UnityEngineCamera.gen.cs:408)
PathMovement.Start () (at Assets/Scripts/PathMovement.cs:21)
This is quite weird since I've attached the main camera, but somehow unity didn't detect that. I also have tried to put the cam = GetComponent<Camera>(); on Awake() as well as Start(), but none work. :(
Btw, I am making a mobile application on android. And using unity 5.
Is there any way to do it properly??
Thanks.
You're getting the MissingComponentException as there is no Camera attached to that particular GameObject (see the description of the Exception).
What you need to know is that GetComponent only looks for that Component in the current GameObject. Depending on your GameObject hierarchy you may want to use GetComponentInParent or GetComponentInChildren instead.
Or you could also attach the Camera using the Editor (drag and drop). This may not work if you instantiate that Prefab during runtime, but should do just fine when its static in the scene.