unity3d,unityscript , Unity: using yield waitforseconds more than once


Unity: using yield waitforseconds more than once

Question:

Tag: unity3d,unityscript

The idea is to create a delay every 2 seconds for Regenerate(), so I can give 2 seconds for the player to catch the scoreObject, otherwise it teleports to the random coordinates.

The problem is that after the first cycle, yield WaitForSeconds(2); gets ignored, making the scoreObject untouchable.

#pragma strict

public var scoreObject : GameObject;

function Update () {
    Regenerate();
}

function Regenerate () {
    yield WaitForSeconds(2);
    scoreObject.transform.position.z = Random.Range(-6.0, 6.0);
    scoreObject.transform.position.x = Random.Range(-4.5, 4.5);
}

Is there any way to get rid of this issue? I want this wait to work every time Regenerate() is used.


Answer:

The problem is that you are starting new WaitForSeconds on every frame. So after 2 seconds there is one wait ending on almost every frame. You can fix this with boolean variable, by doing Regenerate() only when it is true and setting it to false while waiting.

#pragma strict

public var scoreObject : GameObject;

var doRegenerate = true;

function Update () {
    if(doRegenerate) {
        Regenerate();
    }
}

function Regenerate () {
    doRegenerate = false;
    yield WaitForSeconds(2);
    doRegenerate = true;
    scoreObject.transform.position.z = Random.Range(-6.0, 6.0);
    scoreObject.transform.position.x = Random.Range(-4.5, 4.5);
}

Related:


EditorGUILayout.Popup option is not changing


unity3d,unity3d-gui,unity3d-editor
using this simple code I'm showing a dropdown int selected = 0; ///* string[] options = new string[] { "Start With", "End With", "Contains", }; //criteria = EditorGUILayout.Popup("Search Criteria", 2, options); //*/ criteria = EditorGUILayout.Popup("Awesome Drop down:", selected, options, EditorStyles.popup); it showing dropdown with option perfectly but the problem is...

Unity setting GUIText of another object


c#,unity3d
I have (PlanetController): private GameController gameController; ... void OnMouseEnter() { gameController.setClassText("Orbital speed: " + orbitSpeed); } In the GameController script: public class GameController : MonoBehaviour { public GUIText classText; void Start () { this.setClassText (""); } public void setClassText(string text) { classText.text = text; } } But I'm getting: NullReferenceException:...

How do I Mute The Audio In Unity 3D?


c#,audio,unity3d,mute
with script this. what is wrong in script this ? audio.mute = ToggleButton.isSpeakerOff; sorry bad english,fast answer please correct my script please...

Unity WaitForSeconds stuck


c#,unity3d
I tried to create a simple splashscreen. at first this waitforseconds working, but suddenly after a few week this code doesn't want to work. I tried using debug.log but I just get the "before wait" and the "after wait" doesn't appear even after 5 minutes. I am using unity 4.5,...

SWF works locally but not loaded from server


mod-rewrite,unity3d,swf,swfobject
Here is the deal. I have SWF build with Unity and embedded into HTML page with swfobject. It works perfectly well when I load page locally (zip), but it always says "Movie not loaded" when I try to load page. from server I have already inspect similar embedded movies (this...

In Unity3D, How to make the whole scene in dark, but some Area are not in dark


unity3d
I wan't make some teaching levels with UGUI, so need the whole to be in dark, but some rectangular area not in dark. I can make the whole scene in dark by adding a gameobject with a image component, and control it's alpha to dark. But I don't know how...

Loading MP3 files at runtime in unity


c#,unity3d
I'm trying to load an mp3 file at runtime using the WWW class that is provided in Unity. I don't get any errors, but I'm unable to play the music after the song has been processed. I have looked everywhere and cannot find anything to help me. Here is the...

Giving objects unique ids onStart


c#,random,unity3d
I have a bunch of gameObjects that I am assigning unique ids to in the Start function. void Start() { UniqueID = String.Format("{0:X}", DateTime.Now.Ticks); } I thought this would work but every now and then I get duplicate ids. How can I make sure that they are always unique?...

Convert a large int to a float between 0.0f and 1.0f


math,unity3d,numbers
I'm working on a project where I have a pane that goes from 0 to 500 on the x and z, but I need to convert that coordinate (from 0 to 500) to a float in the range of 0.0 to 1.0 in because it is required from some of...

I'm trying to reduce the Length of this Code


c#,unity3d
I wrote some code today. I can't figure out how to reduce the length of this code, although it seems repetitive, every part is different. try { totalVerts.Add(verts[i]); if (verts[i].x > maxXvert) { maxXvert = verts[i].x; } if (verts[i].x < minXvert) { minXvert = verts[i].x; } if (verts[i].y > maxYvert)...

Jump to another scene detecting a rigidbody


c#,unityscript
I am making a little game in c# on unity 5, and until now I have almost everything. How do I jump to another scene on detecting a rigidbody?

how to add Scoring to unity3D 2d top down car game?


unity3d,2d,car,topdown
I'm making 2D top down car game. as for now car game working with if player car hit enemy car game is over. I used for it adding tag to Enemy car and if player car collision detect enemy car with tag the finish the game. My question is: How...

Unity procedural TileMap generation without creating gameobject per tile


unity3d
I've been searching all over the internet to find a efficient way to create procedural tilemap without creating a gameobject per each tile. There is none, or simply i couldn't find it, because i really don't know how to make a search for it. All the TileMap tutorials i found...

When building to mobile the size of fonts reduce and became very small


c#,user-interface,unity3d,uibutton,unityscript
Like I said in the title when i built to mobile the letter became too small. I think it is because phone has more pixel for his little screen. Well I tried to fix text by simply making text to images in photoshop. But how can I make InputFields text...

Create array/list of many objects(initially unknown amount) by tag


c#,arrays,list,unity3d,gameobject
I'm currently working on a radar system for my space game, and I am trying to work out how to add gameobjects, by tag, to either a list or array that can then be used in other methods. I can't do this manually because I will be procedurally generating each...

ant jar error: Execute failed: java.io.IOException: Cannot run program…${aapt}": error=2, No such file or directory


java,android,osx,unity3d,jar
I'm trying to compile a simple Java library for Unity, and after running ant jar, I get the following message: /Applications/adt-bundle-mac-x86_64-20140702/sdk/tools/ant/build.xml:649: The following error occurred while executing this line: /Applications/adt-bundle-mac-x86_64-20140702/sdk/tools/ant/build.xml:694: Execute failed: java.io.IOException: Cannot run program "/Users/****/UnityProjects/****/JavaTestPlugin/${aapt}": error=2, No such file or directory This is strange, because I've compiled this...

Instantiate GameObject at Random time is not working


unity3d
I want the enemy to spawn at random time between 1-5 seconds but when I applied the script inside the game , the game is spammed with enemies and it continuously nonstop spawning enemies ! using UnityEngine; using System.Collections; public class Game_Control : MonoBehaviour { private bool Spawn1=true; public GameObject...

Iterating through multiple levels of Child Objects


c#,unity3d,iterator
I have this block of code. And I need to iterate through every child object, but child objects could have more children within them. The Awake() method is called when the program is first ran. So, I'm asking how to build an iterator that will check if there are children...

Android - Unity3D freeze in splash screen on some phones


android,unity3d,screen,freeze,splash
I have a problem with Unity3D. I created a game with Unity 4.6.2f1. My problem is, game crashes after splash screen(Like trying to open itself constantly). The weird part is, game works on my phones and my tablets perfectly. I have Nexus 5(With Android 5.1.1) , Iocean X7S(With Android 4.2.2)...

Unity3D Play sound from particle


audio,unity3d,collision,particles
I am trying to play a sound when a particle collides with a wall. Right now, it just plays the sound from the parent object, which is the player. However, I want the sound to play from the particle. Which means when a particle is far to the left, you...

How to draw each a vertex of a mesh as a circle


ios,unity3d,shader,mesh,particle
How to draw each a vertex of a mesh as a circle?

Unity: Android and iOS Push Notifications


android,ios,unity3d,push-notification,android-notifications
I'm working on a mobile game with Unity and going to use push notifications. I found NotificationServices class that for iOS only. But I didn't find any server-side code examples for that class. I'm asking for any nice examples or solutions providing server and client-side code (Android client & backend...

Unity: GameObject.FindGameObjectWithTag isn't working and I don't know why


unity3d
I have a enemy AI script and a small part of the code isn't working. It's supposed to search for a game object with the Player tag when the target no longer exists. So, when the player collects a power up and a new player prefab spawns in its place...

Manual slide-in animation using delta time


c#,animation,unity3d
I'm creating a simple slide-in animation for my game. The box is shown at the bottom with character dialog. The animation is supposed to look as follows: A square slides in from the left, then waits a bit, then expands to its full width. The box is made using Unity's...

How expensive is creating class instance? (performance considerations) [closed]


c#,unity3d
In C#, how expensive it is to create new class instance? I'm speaking in context of using C# in unity3d. Meaning that stuff continuously gets called many times per second. In C++, generally speaking (while making games) you may want to reuse anything you created with new/smart pointers, you would...

How to Create Thumbnails in unity


unity3d
I am creating a video player app for android. for that i need to create thumbnails for the videos present in the videos folder. After searching web i could able to understand unity's MovieTexture doesn't support for android. This one i could able to solve using a plugin. For creating...

Unity: Prefab parenting in code


unity3d,gameobject
Let's say I want multiple prefab object called childTile, it parenting another single prefab object called parentTile. So whenever the parentTile rotates, childTiles will be rotated around parentTile. Basically this is what I wrote: public GameObject childPrefab; public GameObject parentPrefab; void Update() { for(int i = 0; i < 10;...

Our iOS developer has developed a game in Unity3D. How do we export it for Android?


unity3d
Our iOS developer has developed a game in Unity3D. How do we export it for Android? I did a quick check on the internet and it says there "one click export for Android". Is this really the case? Are there ways it might have been developed that will make it...

Unity 3D Text becomes Word Cubes


android,unity3d,vuforia
As the image shows, my 3D Text keeps disappearing from my scene when I click Play, and then when I zoom in, this is what I see. When I exit the Play scene, it stays like that till I Ctrl+S and Save on which is returns to its proper text...

Unity3D Bullet Tracers


unity3d,unityscript,raycasting
I'm currently working on implementing the elusive bullet tracer to my FPS. It isn't going so well. a. The tracers align themselves off of the barrel of the Raycast area b. They all aim themselves in the same direction, no matter where I point my cursor This is the formula...

converting string to vector in Unity


vector,unity3d,unityscript
I am trying to convert an array of strings in unityscript with values holding values like: "Vector3(5, 3, 8)" into an array of vectors, but Unity will not take these strings as is. Anyone have any ideas?...

Turning an avatar into a 3rd person character


animation,unity3d
I just learned how easy it is to simply drag a 3rd person character controller prefab (from Unity's standard assets package) and drop it into the hierarchy. Using the WSAD and Space keys feels pretty natural, so I wondered if I could apply the same character controller to a customized...

Unity 5 Audio Volume Slider (Solved)


c#,audio,unity3d
I am trying to create an slider that I can use for volume control in Unity 5 but the volume will not change. My Game Objects are called MainMusicPlayer for the audio source and Volume Slider for the slider I am going to post the whole script as it would...

Unity2D C# - Can't destroy an Instantiated object


c#,unity3d
public class playerAttack : MonoBehaviour { public bool attacking = false; public Transform Player; public Transform swordObject_prefab; Animator anim; GameObject clone = null; // Use this for initialization void Start () { anim = GetComponent<Animator> (); } // Update is called once per frame void Update () { if (!attacking...

Unity 5.1 and OnGUI()


user-interface,unity3d
I had the following simple code working, before upgrading to Unity 5 but now nothing happens when I press the Space key! void OnGUI() { if ( Input.GetKey( KeyCode.Escape ) ) { GUILayout.BeginArea( new Rect(50, 50, 100, 100) ); GUILayout.Button("Exiting!"); GUILayout.EndArea(); } } The script is attached to an empty...

What is this programming method called? And is it bad?


c#,unity3d,modular
Lately in my Unity projects, I have discovered that to create a more modular application it helps to have a static List in a class that contains references to all or some of the objects created so that they may be accessed easily from other parts of the program. An...

Controlling a player using touch input on the mobile device


android,ios,mobile,unity3d,touch
I am new to Unity, and was following the tutorials of roll a ball. I was to create it for both mobile and desktop and it is working but the only problem I have is that I am unable to create touch keys arrows(left,right,up,down) to control the player on the...

Converting from Pixel Coordinates to UI Coordinates in Unity


user-interface,unity3d
Does anyone know how to convert from Pixel Coordinates to UI Coordinates and vice-versa in Unity? Let's say for example I want to click somewhere on the screen with the mouse, and a UI Image to be at that click position. If I do this won't work: Image img =...

Make two physics objects not collide but do detect collisions in Unity


unity3d,2d,physics
I have a Unity project in which there is a 2D game world that consists of static colliders to make the geometry solid to the characters that inhabit it. The player is a dynamic collider (with a non-kinematic rigidbody). There's also an enemy character that is also a dynamic collider....

Formatting large numbers in C#


c#,.net,unity3d,formatting
I am using Unity to make an "Incremental Game" also known as an "Idle Game" and I am trying to format large numbers. For example, when gold gets to say 1000 or more, it will display as Gold: 1k instead of Gold: 1000. using UnityEngine; using System.Collections; public class Click...

Scoring scale object


unity3d
I started working with Unity platform just a few days ago. I want to create and object like this one: (http://www.bankingsense.com/wp-content/uploads/2014/09/credit-score-ratings.png) where the user will choose the appropriate answer. Each option will generate a different score that should be stored for later use. Can anyone give me some tips ad...

var keyword vs actual type? [duplicate]


c#,unity3d
This question already has an answer here: Use of var keyword in C# 86 answers I'm using vim + omnisharp/syntastic for some unity3d development in C#. When I declare a variable using the actual type, for instance string[] myArray = new string[5]; I get a warning message telling me...

Csproj file in unity changes everytime i reload the project


c#,unity3d,msbuildcommunitytasks
I want to change the 'csproj' file of my unity project in order to be able to access a specific library as this answer sugests. I am manually editing the file but every time i reload the project, the 'csproj' file returns to it's initial state. Is this a common...

How to make the whole scene in dark on unity3D


unity3d
Likes that when the game is pause, only the Resume button is lighted, other whole scene is in dark, Is there some function can do it?

Unity An object reference is required to access non-static member C#


c#,unity3d
Im trying to learn C# with Unity engine But a basic script like this: using UnityEngine; using System.Collections; public class scriptBall : MonoBehaviour { // Use this for initialization void Start () { Rigidbody.AddForce(0,1000f,0); } // Update is called once per frame void Update () { } } gives this...

2D game development with Unity3D


unity3d,2d-games
I tried to find some answers to a few questions I have about Unity3D games development. I want to create 2D mobile games. The thing I really want to know is if I can create a mobile game for different platforms at one time (as cordova can build Android /...

AdColony's OnVideoFinished not call in Android


c#,android,unity3d,adcolony
I have a problem with AdColony-UnitySDK. When AdColony's video is finish playing, OnVideoFinished() method don't be called. In this case, the following sources work well in iOS. And also, the server receive the success callback both device. So, only Android device that is not work. Here is the source code,...