How To Respawn A Prefab After 5 Second's? - unity3d

I'm trying to spawn a prefab after I destroy the object and only when the object is destroyed.
#pragma strict
function Update () {
if (Input.GetMouseButtonDown(0)) {
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit)) {
if (hit.collider.tag == "destroyable") {
Destroy(hit.collider.gameObject);
}
}
}
}

You could put the Prefab in a variable to set on unity editor:
var objectToSpawn : GameObject;
Before the Spawn code you can use:
yield WaitForSeconds (5);
Your code would look something like this:
Javascript
#pragma strict
var objectToSpawn : GameObject;
function Update () {
if (Input.GetMouseButtonDown(0)) {
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit)) {
if (hit.collider.tag == "destroyable") {
var oldTransform = hit.collider.gameObject.transform;
Destroy(hit.collider.gameObject);
StartCoroutine(SpawnAfter5Seconds(oldTransform));
}
}
}
}
function SpawnAfter5Seconds(oldTransform:Transform)
{
yield WaitForSeconds (5);
var newObject = Instantiate (objectToSpawn , oldTransform.position, oldTransform.rotation);
}

Related

MissingComponentException: There is no 'SpriteRenderer' attached to the "Balletjes(Clone)" game object, but a script is trying to access it

I get this error:
"MissingComponentException: There is no 'SpriteRenderer' attached to the "Balletjes(Clone)" game object, but a script is trying to access it."
I would like to assign the name of a sprite to the variable goldCoinPopUp. I searched a lot but nothing worked. Can anyone help me please?
ItemDragHandler
public class ItemDragHandler : MonoBehaviour, IDragHandler, IEndDragHandler
{
public GameObject prefab;
Vector2 original;
public void OnDrag(PointerEventData eventData)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Debug.DrawRay(ray.origin, ray.direction * 100);
transform.position = Input.mousePosition;
}
public void OnEndDrag(PointerEventData eventData)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray.origin, ray.direction, out hit, 100))
{
if (hit.collider.gameObject.name == "Terrain")
{
transform.gameObject.SetActive(false);
GameObject obj = Instantiate(prefab,hit.point, Quaternion.EulerAngles(0f, 3f, 0f)); // 3d object
obj.AddComponent<GenerateResources>(); // link to GenerateResources script
Vector3 img = new Vector3(0, 8.66f, 0);
obj.transform.position += img;
}
else
{
transform.localPosition = original;
}
}
else
{
transform.localPosition = original;
}
}
void Start ()
{
original = transform.localPosition;
}
}
GenerateResources
public class GenerateRessources : MonoBehaviour
{
private int ressourcesInBuilding;
public int valueWhenCollect = 10;
private float timerExtraRessource;
public float generateRate = 4;
public SpriteRenderer goldCoinPopUp;
private GameObject currentGameObject;
private GameObject Inventory;
void Start ()
{
goldCoinPopUp = GetComponent<SpriteRenderer>();
goldCoinPopUp.enabled = false;
currentGameObject = gameObject.GetComponent<GameObject>();
Inventory = GameObject.Find("Inventory");
}
void Update ()
{
AddResource();
getResources();
}
private void AddResource()
{
timerExtraRessource += Time.deltaTime;
if (timerExtraRessource >= generateRate)
{
ressourcesInBuilding++;
timerExtraRessource = 0;
if (ressourcesInBuilding >= valueWhenCollect)
{
goldCoinPopUp.enabled = true;
}
}
}
private void getResources()
{
if (Input.touchCount > 0)
{
Touch touch = Input.touches[0];
if (touch.phase == TouchPhase.Began)
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100f))
{
if (hit.transform.gameObject != null)
{
}
}
}
}
if (Input.GetMouseButtonDown(0))
{
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, 100f))
{
if (hit.transform.gameObject != currentGameObject)
{
if (goldCoinPopUp.enabled == true)
{
goldCoinPopUp.enabled = false;
Inventory.GetComponent<GameController>().Gold += ressourcesInBuilding;
ressourcesInBuilding = 0;
}
}
}
}
}
}
Your code depends on SpriteRenderer being present, while your prefab does not have one. You can work around this problem by adding the following attribute before your class definiton
[RequireComponent(typeof(SpriteRenderer))]
public class GenerateRessources : MonoBehaviour
However the automatically added SpriteRenderer will have no sprite attached, hence a better solution would be to make sure your prefab does indeed have a reasonable sprite attached

How to move gun backward when near to wall in unity?

I am making a FPS game in unity. I have wrote a script for gun to move back ward when it is close to a object, And also for enabling gun scope. I have used animation for gun to move back(gunBackward) and to enable scope(Scoper) and also for gun regular position(idleGun). But now in unity when I play the game I am not able to enable scope when Ray hits a collider, The gun starts vibrating. I am only able to enable scope when I look at the sky box.
public float distance;
public GameObject origin;
public bool scop;
public Animator anim;
public GameObject CrossHair;
public bool scoped;
// Use this for initialization
void Start () {
anim = GetComponent<Animator>();
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown ("Fire2")) {
scoped = true;
scop = false;
}
if (Input.GetButtonUp ("Fire2"))
{
scoped = false;
scop = true;
}
if (scoped == true) {
anim.Play ("Scoper");
}
if (scoped == false)
{
anim.Play("idleGun");
}
Vector3 cartPos = new Vector3 (0.0f, 0.0f, 0.0f);
RaycastHit hit;
if (Physics.Raycast (cartPos+origin.transform.position, transform.TransformDirection (Vector3.forward), out hit))
{
distance = hit.distance;
}
if (hit.transform == null) {
distance = 2.1f;
return;
}
if (distance < 2)
{
anim.Play ("gunBackward");
}
if (distance > 2)
{
anim.Play("idleGun");
}
}
}

Unity hit.rigidbody reference to concrete gameObject

I've got Menu with 3d texts. Main Camera has got animations that I want to play after clicking on text. Every text has its own rigidbody and collider. I made this code:
#pragma strict
import UnityEngine;
var object : GameObject;
var Run : AnimationPlay;
function start(){
Run = object.GetComponent(AnimationPlay);
}
function Update() {
if (Input.GetMouseButtonDown(0)) {
var hit: RaycastHit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, hit)) {
if (hit.rigidbody != null){
Debug.Log("Start Game pushed");
Run.action = true;
}
}
}
}
for Start Game button and this one:
#pragma strict
import UnityEngine;
var object : GameObject;
var Run : AnimationPlay2;
function start(){
Run = object.GetComponent(AnimationPlay2);
}
function Update() {
if (Input.GetMouseButtonDown(0)) {
var hit: RaycastHit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, hit)) {
if (hit.rigidbody != null){
Debug.Log("Back pushed");
Run.action2 = true;
}
}
}
}
for Back button.
The problem is it's no matter on which rigidbody I will click, both animations are starting to play and that makes weird effects. I don't know how to make a reference to concrete gameObject's rigidbody.
I solved my problem. I replaced
hit.rigidbody != null
with
hit.rigidbody.gameObject.tag == "StartGame" //object's tag here
and now it works fine.

Refresh to Car Position Correct Way Unity

I created car game. I have 3 checkpoint. Car refresh when I press R key
but car wrong position.
My Code;
Checkpoint.js;
#pragma strict
var SpawnPoint : Transform;
function OnTriggerEnter(col: Collider)
{
if(col.tag =="Player")
{
SpawnPoint.position = Vector3(transform.position.x, transform.position.y, transform.position.z);
}
}
ReSpawn.js;
#pragma strict
var SpawnPoint : Transform;
var player : GameObject;
var target : Transform;
function Update()
{
if(Input.GetKeyDown(KeyCode.R))
{
player.transform.position = SpawnPoint.position;
}
}
How to force correct position?
you should use getcomponent to get a var in another script assign your checkpoint script to var script via inspector.
#pragma strict
var script : Checkpoint;
var player : GameObject;
var target : Transform;
function Update()
{
if(Input.GetKeyDown(KeyCode.R))
{
player.transform.position = script.GetComponent(Checkpoint).SpawnPoint.position;
}
}

Bullet Decal Sideways

When I instantiate a bullet decal texture to the hit point of a raycast it goes sideways for some reason, no online resources have proved to be any help because it works for them.
The texture for the decal is on a plane and it is laying flat above the ground (height at which raycast hit.)
Here's the raycast shooting code:
var TheDammage = 100;
var BulletHole : Transform;
var canShoot : boolean;
var NoShootZoneTrigger : Transform;
//var AmmoText : GUIText;
var Ammo : float;
var MaxDistanceInMetersMax35 = 25;
var GunFirePistol : AudioClip;
var DryGunFirePistol : AudioClip;
function Start() {
canShoot=true;
}
function Update () {
if (MaxDistanceInMetersMax35>25){
MaxDistanceInMetersMax35 = 35;
}
var hit : RaycastHit;
var ray : Ray =
Camera.main.ScreenPointToRay (Vector3(Screen.width*0.5, Screen.height*0.5,0));
//AmmoText.text = "Bullets Remaining: "+Ammo;
if (Input.GetMouseButtonDown(0)&& canShoot==true){
if (Physics.Raycast(ray, hit, 100)){
if (Ammo >0){
Ammo--;
audio.PlayOneShot(GunFirePistol);
}
{
Debug.Log(hit.distance);
if (hit.distance<MaxDistanceInMetersMax35){
var particleClone = Instantiate(Effect, hit.point,
Quaternion.LookRotation(hit.normal));
Destroy(particleClone.gameObject, 15);
hit.transform.SendMessage("ApplyDammage",
TheDammage, SendMessageOptions.DontRequireReceiver);
}
}
if (Input.GetMouseButtonDown(0)&& canShoot==false){
Debug.Log("No Shooting Zone!");
}
}
if (Input.GetKeyDown("w")){
canShoot = false;
}
if (Input.GetKeyUp("w")){
//animation.Play("GunWalkDone");
canShoot=true;
}
}
if (Ammo<1){
canShoot=false;
if (Input.GetMouseButtonDown(0)&& canShoot==false){
//AmmoText.text="";
audio.PlayOneShot(DryGunFirePistol);
}
}
if (Ammo<18) {
if (Input.GetKeyDown("r")){
animation.Play("Reload");
}
}
}