Spawning object and Destroing player character - c#

I writing runner.
I have two problems
I have spawning object (quad).
1) I try to spawn my object many times , but it spawning once.
My Spawn script:
using UnityEngine;
using System.Collections;
public class SpawnScript : MonoBehaviour {
public GameObject[] obj;
public float spawnMin = 1f;
public float spawnMax = 2f;
// Use this for initialization
void Start () {
Spawn();
}
void Spawn()
{
Instantiate(obj[Random.Range(0, obj.GetLength(0))], transform.position, Quaternion.identity);
Invoke("Spawn", Random.Range(spawnMin, spawnMax));
}
}
I try to make spawning script, like here Spawning but facing second problem
And second problem
2) I have destroyer script, I use it on spawning quad. On first object Player character destroys, on second object it through it.
Destroyer script
using UnityEngine;
using System.Collections;
public class DestroyerScript : MonoBehaviour {
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player") {
Destroy(other.gameObject);
Application.LoadLevel(1);
return;
}

For the spawning problem, you can use a coroutine.
void Start()
{
StartCoroutine(Spawn());
}
IEnumerator Spawn()
{
// Instantiate your game objects
Instantiate(obj[Random.Range(0, obj.GetLength(0))], transform.position, Quaternion.identity);
// Wait for a random time interval
yield return new WaitForSeconds(Random.Range(spawnMin, spawnMax));
}
For the collision problem, my guess is, the quad is destroyed by the player in player's collision script.

Related

The Object you want to instantiate is null. (Error Unity)

I've tried to fix this problem for many days, looked for every result in a web and didn't get any suitable answers to me...
With this problem I can run my game, but it shows up every time I shoot the bullet prefab.
This is a player shooting script, it shows up a problem when I try to Instatiate(bulletRef);
public GameObject bulletRef;
// Start is called before the first frame update
void Start()
{
bulletRef = Resources.Load("Bullet") as GameObject;
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Z))
{
// By pressing the button we create an instance of a bullet
Instantiate(bulletRef);
bulletRef.transform.position = new Vector3(transform.position.x + .4f, transform.position.y + .2f, -1);
}
}
I think that those codes look suspicious to me, maybe the roots of this problem are coming out from them
here is a script for bullet
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BulletScript : MonoBehaviour
{
public float speed = 20f;
public int damage = 1;
public Rigidbody2D rb;
// Start is called before the first frame update
void Start()
{
rb.velocity = -transform.up * speed;
}
private void OnTriggerEnter2D(Collider2D collider)
{
Destruction enemy = collider.GetComponent<Destruction>();
if (enemy != null)
{
enemy.TakeDamage(damage);
}
Destroy(gameObject);
}
}
This is a script for destroying the bullet. I don't personally think that there is an issue with this code, but it is for you to understand how my bullet dissapears
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Destruction : MonoBehaviour
{
public int health = 1;
public void TakeDamage(int damage)
{
health -= damage;
if (health <= 0)
{
Die();
}
}
void Die()
{
Destroy(this.gameObject);
}
private void OnTriggerEnter2D(Collider2D collision)
{
ScoreManager.instance.AddPoint();
}
}
The problem lies in your Update() method of your first script
Instantiate(bulletRef);
bulletRef.transform.position = new Vector3(transform.position.x + .4f, transform.position.y + .2f, -1);
You are instantiating the gameobject bulletRef but not assigning it to any field. Also, you are changing the position of just a reference to the gameobject you just loaded from the resources. You didn't have a reference to the gameobject in the scene, you have a reference to the gameobject in your resources. To get a reference to the gameobject you just instantiated into your scene, assign the instantiated gameobject to a field. But the function Instantiate returns an Object hence we typecast it to GameObject as
GameObject bulletRefObject = Instantiate(bulletRef) as GameObject;
bulletRefObject.transform.position = new Vector3(transform.position.x + .4f, transform.position.y + .2f, -1);

Unity 3D shoot and destroy enemy do not work

I have a Player who uses a weapon to shoot and destroy enemies. I have a code for a gun:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour {
float bulletSpeed = 60;
public GameObject bullet;
void Fire(){
GameObject tempBullet = Instantiate (bullet, transform.position, transform.rotation) as GameObject;
Rigidbody tempRigidBodyBullet = tempBullet.GetComponent<Rigidbody>();
tempRigidBodyBullet.AddForce(tempRigidBodyBullet.transform.forward * bulletSpeed);
Destroy(tempBullet, 5f);
}
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Fire();
}
}
}
and the code for bullets:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Bullet : MonoBehaviour
{
private void OnTriggerEnter(Collider other)
{
if (other.tag == "Enemy")
{
Destroy(gameObject);
}
}
}
even though my enemy is tagged as 'enemy' and has a box collider triggered it doesnt disappear. The bullet prefab has rigidbody and sphere collider. Please help :)
If you use Destroy(gameObject) you are destroying the bullet.
In order to destroy the enemy you should do a
Destroy(other.gameObject)
So you will destroy the object that actually triggered, the enemy
You are telling the bullet to destroy itself. You probably rather wanted
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Enemy"))
{
// Destroy the thing tagged enemy, not youself
Destroy(other.gameObject);
// Could still destroy the bullet itself as well
Destroy (gameObject);
}
}

Making Destroyer (UnityC#)

I making simple runner game.
I want do have some block over which player which jump.
I make a prefab and quad.
Attached Spawn script:
using UnityEngine;
using System.Collections;
public class SpawnScript : MonoBehaviour {
public GameObject[] obj;
public float spawnMin = 1f;
public float spawnMax = 1f;
// Use this for initialization
void Start ()
{
Spawn();
}
void Spawn()
{
Instantiate(obj[Random.Range(0, obj.GetLength(0))], transform.position, Quaternion.identity);
Invoke("Spawn", Random.Range(spawnMin, spawnMax));
}
}
Also I attached Destroyer script:
using UnityEngine;
using System.Collections;
public class DestroyerScript : MonoBehaviour {
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
Application.LoadLevel(1);
return;
}
if (other.gameObject.transform.parent)
{
Destroy(other.gameObject.transform.parent.gameObject);
}
else
{
Destroy(other.gameObject);
}
}
}
But when player enter this object nothing happens.
Screen of my Quad:
Where is my mistake?
You use OnTriggerEnter2D. If your collider not ticked isTrigger field, you can use OnCollisionEnter2D.
And also if your object has Normal (3D) collider you need to use 3D versions of them.
OnTriggerEnter or OnCollisionEnter.
And also you should read this.
UPDATE
After discussion and looking your project problem is your character doesnt hit the destroyer object's collider. It moves with your main camera. (Destroyer object is child object of camera). Because of that when you take your destroyer from camera's child object it works.
Any child object in the heirarchy inherits it's parents movement. So if the collider is on a child object of the camera, it will move when the camera moves.

Programming a 2d enemy in c#

I have been working on enemies in my game, but feel the code is clunky as is and also does not seem to work. I put code into my player script and enemy script. the player script is as follows:
EDIT: sorry for not being clear enough, here are the lines of code that do not work and what I want them to do:
void OnTriggerEnter2D (Collider2D other)
{
if (other.gameObject.tag == "Enemy")
{
Destroy (this.gameObject);
}
}
What i want in this code is for when the player encounters an enemy or object with the "Enemy" tag, touching that object will destroy or kill the player object.
void OnTriggerEnter2D (Collider2D other)
{
if (other.gameObject.tag == "Killable")
{
Debug.Log ("entering killzone!");
Destroy (other.gameObject);
Instantiate (DeadStar, transform.position, Quaternion.identity);
this.gameObject.SetActive (false);
}
}
}
This code was loosely copied from a previous game, this has bits of it's killzone and was made to destroy the player object when it touches any object that contains this script. (the player is tagged "Killable")
hope this edit helps, im a little tired and forgot to specify things, sorry about that.
using UnityEngine;
using System.Collections;
public class PlayerController : MonoBehaviour
{
public float JumpSpeed;
public float Scale;
public string JumpKey;
public string LeftKey;
public string RightKey;
public float speed;
public GameObject Player;
public Rigidbody2D rb;
void OnTriggerEnter2D (Collider2D other)
{
if (other.gameObject.tag == "Enemy")
{
Destroy (this.gameObject);
}
}
void Start()
{
GetComponent<Rigidbody2D>().freezeRotation = true; /*GetComponent<Rigidbody>().angularVelocity = Vector3.zero;*/
rb = GetComponent (typeof(Rigidbody2D)) as Rigidbody2D;
}
void FixedUpdate ()
{
Vector3 hold = rb.velocity;
hold.x = 0;
if (Input.GetKey (LeftKey))
{
hold.x -= speed;
}
if (Input.GetKey (RightKey))
{
hold.x += speed;
}
if (Input.GetKeyDown (KeyCode.Space))
{
hold.y = JumpSpeed;
}
rb.velocity = hold;
}
}
The enemy script is as follows:
using UnityEngine;
using System.Collections;
public class EnemyKillzone : MonoBehaviour {
public GameObject DeadStar;
public GameObject Player;
void OnTriggerEnter2D (Collider2D other)
{
if (other.gameObject.tag == "Killable")
{
Debug.Log ("entering killzone!");
Destroy (other.gameObject);
Instantiate (DeadStar, transform.position, Quaternion.identity);
this.gameObject.SetActive (false);
}
}
}

Unity 3D Instantiated Prefabs stop moving

I set up a pretty simple scene where a prefab is being instantiated every x seconds. I applied a transform.Translate on the instances in the Update() function. Everything works fine until a second object is spawned, the first one stops moving and all the instances stop at my translate value.
Here is my script, attached to an empty GameObject:
using UnityEngine;
using System.Collections;
public class Test : MonoBehaviour {
public GameObject prefab;
private Transform prefabInstance;
void spawnEnemy() {
GameObject newObject = (GameObject)Instantiate(prefab.gameObject, transform.position, transform.rotation);
prefabInstance = newObject.transform;
}
void Start() {
InvokeRepeating ("spawnEnemy", 1F, 1F);
}
void Update () {
if (prefabInstance) {
prefabInstance.transform.Translate (new Vector3(4,0,0) * Time.deltaTime);
}
}
}
Your movement is occuring on the prefabInstance object in your Update(), however, that object gets overwritten when the second instance is created, so only your last instantiated prefab will move.
You should consider splitting your code into 2 scripts, the first one to spawn the prefab, and the second script actually on the prefab to move it.
public class Test : MonoBehaviour {
public GameObject prefab;
void spawnEnemy() {
Instantiate(prefab, transform.position, transform.rotation);
}
void Start() {
InvokeRepeating ("spawnEnemy", 1F, 1F);
}
}
and put this script on your prefab:
public class Enemy : MonoBehaviour {
void Update () {
transform.Translate (new Vector3(4,0,0) * Time.deltaTime);
}
}

Categories

Resources