How can I respawn an object in Unity? - c#

I am working on a 3d basketball game in unity.
It has a score and a timer. After a certain time my scene loads and starts from the beginning. Every time I throw the ball, I have to spawn it.
It has a spawn button and a shoot button. But I don't want to use the spawn button. So I want to spawn the ball automatically.
How should I do it? I am giving my spawn button code and throw button code bellow.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnButton: MonoBehaviour
{
public GameObject ball;
public GameObject BallPosition;
public void Spawn()
{
ball.transform.position = BallPosition.transform.position;
var ballPosition = ball.transform.position;
ball.GetComponent<Rigidbody>().useGravity = false;
ball.GetComponent<Rigidbody>().velocity = Vector3.zero;
ball.transform.position = ballPosition;
}
}
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThrowButton: MonoBehaviour
{
static Animator anim;
public GameObject ball;
public float ballThrowingForce = 5f;
internal bool holdingBall;
void Start()
{
anim = GetComponent<Animator>();
ball.GetComponent<Rigidbody>().useGravity = false;
}
public void Throw()
{
anim.SetTrigger("isThrowing");
StartCoroutine(Test());
}
IEnumerator Test()
{
yield return new WaitForSeconds(1.5f);
ball.GetComponent<Rigidbody>().useGravity = true;
//ball.GetComponent<Rigidbody>().AddForce(transform.up * ballThrowingForce);
ball.GetComponent<Rigidbody>().AddForce(0, 380.0f, ballThrowingForce);
}
}

To spawn a ball you should create a prefab and instantiate it. Example:
private class Spawner : MonoBehaviour
{
public GameObject prefab;
public GameObject Spawn() => Instantiate(prefab);
}
So that your throw code should spawn a ball and if you want destroy an older one.

The above answer by Iv Misticos mentioned the use of Instantiate which is a great way to spawn a new ball.
before you spawn a new ball, you need to specify when it must spawn.
Either you can
use a Invoke("SpawnNewBallMethod",3) //after this piece of code is executed, it waits for 3 seconds and executes the method you mention in it which can have the code to instantiate.
Or After the first ball's work is done, you can destroy it(Destroy(ball)) or set active to false - Then check the state (if it exists(null check?) or gameObject.active==true) and accordingly instantiate a new ball (if it is setactive(false) don't forget to destroy it later).
Although gameObject.active is obsolete, it will serve the purpose without complicating things.
In my opinion, Invoke is better than a IEnumerator here as Invoke will not stop the execution flow and continue with the other things while the timer is running.

Related

How can i un do a destroy() function in C#

I need to destroy an object, in my case is "Player2" witch is in the same scene as "Player1" and then after Player1 position.x is past "baraj".position.x reapear. Basically how can i make a temporarly destroy method.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class switchCameras2 : MonoBehaviour
{
public GameObject baraj;
public GameObject CameraOne;
public GameObject CameraTwo;
public GameObject Player1;
public GameObject Player2;
public void Start()
{
CameraOne.SetActive(true);
CameraTwo.SetActive(false);
}
void Update()
{
if (GameObject.Find("Player1").transform.position.x > GameObject.Find("baraj").transform.position.x)
{
CameraTwo.SetActive(true);
CameraOne.SetActive(false);
}
if (GameObject.Find("Player1").transform.position.x < GameObject.Find("baraj").transform.position.x)
{
Destroy(Player2);
}
if (GameObject.Find("Player1").transform.position.x > GameObject.Find("baraj").transform.position.x)
{
Destroy(Player1);
}
}
}
If you want to Destroy it then you should make a new one with Instantiate method. If you don't want to Destroy it, one alternative is to deactivate it with SetActive like this Player1.SetActive(false); and then enable it like this Player1.SetActive(true);
Try creating a new GameObject variable called "U". And then right before destroying or in the start do U = player2.gameObject;
Now let's say you destroyed it and want to spawn. To do that we do
player2 = U.gameObject;
Instantiate(player2);
That will spawn player 2.
But as mentioned in the other answer .SetActive(false); would make things easier. Anyway if you still want to use destroy then that is how to do that. Good luck

No access to bool in another script

I try to create a shop system where you can buy a character to play with. When I buy a character in the Shop Scene, the bool value in the Inventory script is set to true. When I switch to the Level1 Scene, my character is not spawned. I suppose there is a bug in my GameManager script but I can not find it. Can you please help me? I do not know any more.
GameManager script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
public GameObject Joli;
public GameObject Ninn;
public GameObject Spaci;
public GameObject Woodie;
public GameObject Plumbt;
public GameObject canvasObject;
public Inventory myInventory;
// Start is called before the first frame update
void Start()
{
myInventory = GameObject.FindObjectOfType<Inventory>();
if (myInventory.GetNinn() == true)
{
GameObject Ninnnew = Instantiate(Ninn, Ninn.transform.position, Quaternion.identity) as GameObject;
Ninnnew.transform.SetParent(canvasObject.transform, false);
}
if (myInventory.GetSpaci() == true)
{
GameObject Spacinew = Instantiate(Spaci, Spaci.transform.position, Quaternion.identity) as GameObject;
Spacinew.transform.SetParent(canvasObject.transform, false);
}
}
}
There is currently not enough information / code in your question, but when you change scene, your objects are destroyed by default, and new ones are isntantiated, effectively resetting any values that are set in them.
You need to prevent your Inventory or any object holding data you need to keep that it should not be destroyed when switching scenes, by using DontDestroyOnLoad for instance :
https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html

how follow the instantiated object to other instantiated object

i want to follow the instantiated ball to my instantiated player. when my ball follow the player from hierarchy it work fine but when i instantiate the player it does not work .
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExtraBallController : MonoBehaviour
{
public Transform target;
private int distance = 30;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
this.transform.position = new Vector3 (target.transform.position.x, target.transform.position.y, distance);
}
}
As #Hellium said, there are numerous possibilities. One way is to set the balls' target when the player is instantiated.
Here's a sample code (Not Tested):
GameObject player = Instantiate(playerPrefab, vectorPos, Quaternion.Identity);
ExtraBallController[] balls = FindObjectsOfType(typeof(ExtraBallController)) as ExtraBallController[];
foreach(ExtraBallController ball in balls){
ball.target = player.transform;
}
Hope this helps!

Player Respawn and Death when falling

I'm going through the worse struggle right now. I'm trying to create a game with pitfalls that if the players fall through, they respawn and the game counts their death. I'm completely at wit's end and don't know where to even start with this. The game is 3D
using UnityEngine;
using System.Collections;
public class Respawn : MonoBehaviour {
public Transform spawnPoint;
public float minHeightForDeath;
public GameObject player;
void Start () {
}
// Update is called once per frame
void Update () {
if (player.transform.position.y < minHeightForDeath) {
player.transform.position = spawnPoint;
}
}
}
Use a collider on a plane/cube/whatever works for you, and set it to be a trigger. So when they pass through the trigger collider, it can record them and do what you want with it.
Use the OnTriggerEnter method script
void OnTriggerEnter(Collider other)
{
other.transform.position = spawnPoint.position;
}
You are not putting any data in the "minHeightForDeath" float. Unless you do it in the editor.
Other than that, have you put the script on the player gameObject? And have you set what you have to in the editor?

Unity 2D - How to play death animation prefab

I have created a prefab with animation from sprite sheet, which I want to be played when the Player dies. I checked if the prefab is working by dragging it in the Scene, and it is correctly playing every frame of the sprite sheet in a loop endlessly.
Now I want to play this prefab when the Player dies, and after it ends to destroy it, but so far I am only able to place it where the player dies, and it stays there forever. Also there are some errors when that happens.
Here is the death script:
public class DmgByCollisionEnemy : MonoBehaviour {
public GameObject deathAnimation;
void Die() {
deathAnimation = (GameObject) Instantiate(deathAnimation, transform.position, transform.rotation);
//Destroy(deathAnimation);
Destroy(gameObject);
}
}
I set the deathAnimation by dragging a prefab in the Unity interface.
The error I am getting when the Die() method fires is
UnassignedReferenceException: The variable deathAnimation of DmgByCollisionEnemy has not been assigned.
You probably need to assign the deathAnimation variable of the DmgByCollisionEnemy script in the inspector.
So how can I do that properly?
You can try to add simple destroy script to Your death animation object that destroys object after time or trigger it in animation (Unity Manual: Using Animation Events). When you instantiate object it will appear on desired position and it will be destroied regardless to "main" object.
Destroy Script like this:
void DestroyMyObject()
{
Destroy(gameObject);
}
Script to run after time:
void Start()
{
Invoke ("DestroyMyObject", 1f);
}
void DestroyMyObject()
{
Destroy(gameObject);
}
Spawn script:
using UnityEngine;
using System.Collections;
public class SpawnExtra : MonoBehaviour {
public GameObject deathAnimation;
public static SpawnExtra instance;
void Start ()
{
instance = this;
}
public void SpawnDeathAnimation(Vector3 position)
{
Instantiate (deathAnimation, position, Quaternion.identity);
}
}
And you can use it when you want to spawn additional object like this:
SpawnExtra.instance.SpawnDeathAnimation (transform.position);
Now you have to add gameobject e.g ExtrasController, add script on it and you can spawn whatever you want. Remember to drag&drop animation prefab in inspector.

Categories

Resources