My player object has started to act weirdly and now when I respawn the object (after a death) the instantiated version has some components turned off. In this case its main script and audio source.
![alt text][1]
picture on left is the game object as seen in edit mode. Picture on right is the prefab as seen in edit mode.
![alt text][2]
picture on left is the instantiated object during runtime. Pic on right is the prefab during runtime.
the controller script -
public GameObject playerShip;
public Transform respawnPoint;
void OnTriggerEnter (Collider other)
{
if (other.tag == "Bolt")
{
Instantiate(playerExplosion, transform.position, transform.rotation);
Destroy(other.gameObject);
Destroy(gameObject);
Instantiate(playerShip, respawnPoint.transform.position, respawnPoint.transform.rotation);
LivesManager.lives -= 1;
}
Why is the clone turning off its script and audio source ???
[1]: /storage/temp/44150-p1.png
[2]: /storage/temp/44152-p2.png
↧
Instantiated Object turning off scripts and audio source?(Solved)
↧
Robocraft-Like Block Builder
Does there exist, for free or for pay, any scripts out there that would mimic Robocraft's create-a-ship? I'm not a coder and I was wanting to find some kind of framework to test some block designs to see if this is the way I want to go for creating custom crafts, or to look at a different system entirely.
↧
↧
When does a material gets cloned?
Sometimes I have an object with its material named "something - Clone".
So, as the title states, how does it determine when to create a clone and when not?
↧
How to follow clone object with camera.
I am trying to figure out how to make my camera follow a cloned prefab, but to no avail.
Is there something I should add to the code to help it find cloned objects?
using UnityEngine;
using System.Collections;
using ORKFramework;
public class CameraFollow : MonoBehaviour {
public Transform target;
public float m_speed = 0.1f;
Camera mycam;
// Use this for initialization
void Start ()
{
mycam =GetComponent ();
}
// Update is called once per frame
void Update () {
mycam.orthographicSize = (Screen.height / 2f) / 1f;
if (target) {
transform.position = Vector3.Lerp (transform.position, target.position, m_speed) + new Vector3 (0, 0, -10);
}
}
}
↧
Variable being shared between clones
var selected : boolean = false;
..
function Update () {
..
if(Input.GetMouseButtonDown(0)){
if(Physics2D.OverlapPoint(Camera.main.ScreenToWorldPoint(Input.mousePosition))) {
selected = !selected;
}
}
..
if(Input.GetKeyDown("g")) {
Instantiate(GetComponent("Transform"));
}
}
All clones of the GameObject toggle their selected state when anyone is clicked.
Thanks in advance.
↧
↧
Script finds a non-existing object
I have a really weird problem with my game. I'm using GameObject.FindWithTag in the Update() to find the player transform for my camera script. This is obviously very basic stuff. But now, for some reason, the script finds an object called Player(clone), that doesn't exist in the current scene. Every other script and object in the scene works fine. If I manually drag the player in inspector view, it works fine. If I double click the transform variable in the script that currently is Player(clone), it shows an animator controller in the inspector view and no other components. It just doesn't make any sense. The name Player(clone) would indicate that it would be an object created using Instantiate, but I haven't used it at all. I have no idea how to fix this.
Also, I can't believe that "wtf" was an actual approved suggested tag.
↧
How to clone a gameobject in runtime (not with instantiating)
Hi,
I'm instantiating a game object and performing a boolean mesh operation on it (effectively making a hole in it) and saving it as a new game object (all in runtime).
How can I clone this new game object in runtime?
Thanks!
↧
Editing (clone) properties after runtime
So I have an object with a disabled script in scene and a UI button that enables it by dragging the original object into the inspector and setting it to "Script.bool.enabled" so that the user can activate this function during the game and it isn't always active. This works fine on the original object, however I have set this object to be cloned 19 times in the level and when the user clicks the bool.enable button it activates the script only for the original object and none of the clones like I need it to. Since I can't drag the object(clone) into the inspector while editting, how would I make it so that the user can activate these scripts during runtime?
↧
(solved)Instantiate prefab "on top" of previous one
Hey everyone!
As a coding beginner, I'm stuck with this problem, and I bet you guys can help me out easily.
I have several Prefabs containing a plane with an animated textures on it. When I press the corresponding keyboard button, a clone gets instantiated ( f.ex. I press the spacebar -> prefab_1 gets instantiated). If I press another keyboard key, the newer instantiated prefab should be placed "on top" ( +1 on the z-axis) of the previous instantiated prefab and so on...
I do have managed to get the instantiation of the prefabs, but I'm stuck with the +1 on the z-axis / "on top" part. right now, they have a fixed "spawn" position.
Here's my code:
using UnityEngine;
using System.Collections;
public class Ccontroller : MonoBehaviour {
public Rigidbody ani01;
public Rigidbody ani02;
void Update() {
if (Input.GetButtonDown("Fire1")) {
Rigidbody clone;
clone = Instantiate(ani01, new Vector3(0, 0, 3),Quaternion.identity) as Rigidbody;
}
if (Input.GetButtonDown("Fire2")) {
Rigidbody clone;
clone = Instantiate(ani02, new Vector3(0, 0, 3),Quaternion.identity) as Rigidbody;
}
}
}
additional info: It's an orthographic camera in the scene and all the prefabs have a script attached, which give them a tag and destroys older clones of the same prefab in the scene when the same button is pressed twice. so there is always just 1 clone of the same prefab in the scene.
If you guys could help me out, that would be super awesome!
↧
↧
Instantiate clones 4 times?
Hey
I've got this code to instanstiate an object, it worked fine the other day. Though now it instantiates the object 4 times instead of just once...
Here's my code:
var foundation : Transform;
var foundation1 : Transform;
function Start (){
foundation1.gameObject.GetComponent(Drag).enabled = false;
foundation1.gameObject.active = false;
}
function OnGUI (){
if (Input.GetKeyDown ("return") && foundation1.gameObject.active == true) {
var mousePos = Input.mousePosition;
mousePos.z = 12.701;
var objectPos = Camera.main.ScreenToWorldPoint(mousePos);
var myObject= Instantiate(foundation, objectPos, Quaternion.identity);
}
if (GUI.Button(Rect(100,80,100,25), "Foundation")){
if (foundation1.gameObject.GetComponent(Drag).enabled == true){
foundation1.gameObject.GetComponent(Drag).enabled = false;
foundation1.gameObject.active = false;
}
else{
foundation1.gameObject.active = true;
foundation1.gameObject.GetComponent(Drag).enabled = true;
}
}
}
↧
Instantiate gameObject and destroy clone on click
Hi,
i want to Instantiate GameObjects from prefabs by a List. This are some kind of units, which will have stats and can do some actions.
When one Clone is clicked, only this Clone should get destroyed or what the ever.
By now, every Clone gets destroyed on click.
I've seen some scripts which checks the RayCast of the mouse but
a) i dont get it working
b) its seems to be wrong to do this like this ;)
function SpawnUnits() {
var unitData = JSON.Parse(_netCode.GetUnitData());
var factions = unitData["units"].Count;
var units : int;
var _unitHandlerGO = Resources.LoadAssetAtPath("Assets/prefabs/UnitHandler.prefab", typeof(GameObject));
var unit = 0;
var c = new Array();
c[0] = Color.blue;
c[1] = Color.red;
for (var i : int = 0;i < factions;i++) {
units = unitData["units"][i].Count;
for (var k : int = 0;k < units;k++) {
//Debug.Log(unit);
var _unitHandler : GameObject;
var _unitHandlerScript : Unit;
_unitHandler = Instantiate(_unitHandlerGO, new Vector3(parseInt(unitData["units"][i][k]["position"]["x"]) * _tileSize, 0, parseInt(unitData["units"][i][k]["position"]["z"]) * _tileSize), Quaternion.identity);
_unitHandler.name = "unit"+unit;
_unitHandler.transform.Find("Unit Model").GetComponent.().material.color = c[i];
_unitHandlerScript = _unitHandler.GetComponent.();
_unitHandlerScript.Init(i, unit, unitData["units"][i][k]["name"], unitData["units"][i][k]["type"], unitData["units"][i][k]["melee"], unitData["units"][i][k]["ballistic"], unitData["units"][i][k]["health"]);
unit++;
//Destroy(_unitHandler);
}
}
}
And from Script, which is attached to the prefab which get spawned.
function Update() {
if(Input.GetMouseButtonDown(0)) {
//var ray : Ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//var hitInfo : RaycastHit;
//var collider : Collider = GetComponent.();
//Debug.Log(Physics.Raycast(ray, hitInfo, Mathf.Infinity));
//if(Physics.Raycast(ray, hitInfo, Mathf.Infinity)) {
//Destroy(gameObject);
Debug.Log(this.name);
//Debug.Log("Selected: " + _id + " " + _name);
//}
}
}
So, if there is some bad practice in, please tell me also. ;)
↧
how to keep cloning even the real one has destroy c#
i try to make infinite object with clone as enemies. But when the real object has been destroyed, cloning has stop. I try this code to clone the object.
using UnityEngine;
using System.Collections;
public class Spawner : MonoBehaviour {
public GameObject enemy;
void Start(){
StartCoroutine (EnemySpawn ());
}
IEnumerator EnemySpawn(){
while(true)
{
Instantiate (enemy, transform.position, Quaternion.identity );
yield return new WaitForSeconds(3f);
}
}
}
↧
GameObject parenting during runtime
Hi, this is my very first post in unityAnswers, and I'm quite new to unity. Hope you guys can help me out.
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; i++)
{
GameObject clone = Instantiate(childPrefab, /*PsuedoCode: random position*/ , Quaternion.identity)
clone.transform.parent = parentPrefab;
}
}
The expected result is during runtime, if I rotate parentPrefab at the scene, the 10 childPrefabs should also rotate. I've tried many ways but failed, unless I manually drag childPrefabs to parentPrefab on the Hierachy bar.
Thanks.
↧
↧
Destroy Cloned Object on Collision
hello uniters,
i would like to destroy an object that is cloned on collision **the specific object is cloned beforehand, and i would like to destroy the one specific that collides with the player**. now i have the problem that sometimes another cloned object gets destroyed instead. not the one actually triggering the onCollision Destroy.
[here you can check out what i got so far][1]
**this is my function:**
function OnCollisionEnter(collision:Collision)
{
if( collision.gameObject.tag == "Player" )
{
Instantiate(GameObject.FindWithTag("Exp"), transform.position, Quaternion.identity);
Destroy(collision.gameObject.Find("ShootBomb(Clone)"));
}
}
additional ramble:
*Obviously far from finished, the art,music and fonts are either from public tutorials or the asset store / my iTunes library and not credited yet, as i plan to replace them, once the mechanics work as they should.
and really the only two things in my way are the wrong destructions of the bombs, and an animated player character.
(the game is initially made for android (specifically the htc one mini) so you need to move the player to trigger a bomb, on the phone the mechanics work a bit better, as the gyro acceleration makes it extremely difficult to keep the player in place.*
[1]: https://dl.dropboxusercontent.com/u/62592097/LittleWorldPrelude/LittleWorldPrelude.html
↧
instantiated gameobjects(clone) don't have components of its original gameobject.
Hey guys... I have 10 same objects in scene. I have a script that is attached to all those objects and some of the code of that script is as follows:
Destroy (gameObject);
Object.Instantiate (gameObject, position, Quaternion.identity);
after destroying those 10 gameobjects, I instantite those objects at same time as shown in code. but, the problem is that when I instantiate those gameobjects, they have disabled components of destroyed gameobjects like script, audio source etc. I got a solution that shows that if i first instantiate object and then destroy the original ones, then this problem is solved. But its not suitable solution for me because if i first instantiate and then destroy originals, then the new instantiated objects wont stay on floor, they fall, as I have tried it. So I want a solution of it that gives ENABLED COMPONENTS of new instantiated gameobjects. pls help if any one have a solution.
↧
Moving a transform behaves odd
Working on a 2D game.
So I have a Unit object prefab. The unit has a child object with a GUITexture (it's health bar)
I move the health bar guitexture if the unit moves like so:
public void LateUpdate () {
// if(!isSelected)
// return;
_lbl.SetActive(isSelected);
_pos = Camera.main.WorldToViewportPoint(transform.position);
_pos.z = 0f;
_pos.y = _pos.y+0.05f;
_lbl.transform.position = _pos;
}
The _lbl is the child object that contains the health bar.
When it was just a single object in the scene this worked perfectly. But whenever I instantiate a unit on runtime the health bar moves all jittery. Even if I drag a new object in the scene and save the scene the new object has the jitter. If i close unity and restart it and start the scene the new unit's health bar moves smooth again.
Since all units need to be dynamically instantiated this is a problem.
So to summarize:
Original object works like a charm, Object (clone) has weird jitter.
Any help with this conundrum would be greatly appreciated!
↧
Copying GameObjects with reference types
I have a MonoBehaviour, which contains nested lists of references to classes. My serialization works fine, but when i copy my GameObject the references in those lists now points to same objects. I would like to create deep copies of those objects.
I could do this manually by using editor scripts, but i would like to have it working when manually copying gameobject inside Unity.
How does Unity duplicate lists? Can i somehow take part in this process?
↧
↧
Return a Hashtable. Warning: Implicit downcast from Object to String.
Here's the simplified version of the code:
var h:Hashtable = new Hashtable();
h = returnHash();
function returnHash():Hashtable{
var h2:Hashtable = new Hashtable();
h2.Add("key",1);
return h2;
}
When I do this then the game just freeze at that point. Any help or work round would be appreciate
↧
Destroy instantiated object instead of prefab
Hello, I'm trying to write a script that gives the user two choices. The user either chooses left or right and then it repeats. However, I'm trying to do the following:
1. Destroy both objects when the user either presses left or right
2. Make sure that both choices are not the same (e.g. left and right choices cannot both be healthy food)
So I'm trying to work on the first item and I'm having a lot of trouble. I'm ***REALLY*** new to scripting and C# in general so I'm not sure how to destroy the cloned objects instead of the prefab. I had a function for destroying the objects but it just deleted the prefabs instead. After that, I tried having a separate script for destroying objects that would be applied to cloned objects but I'm not sure how to apply them to cloned objects. I could really use some help here on the first part (and if you're feeling generous the second part).
Here's my code:
using UnityEngine;
using System.Collections;
public class randomFood : MonoBehaviour {
public float randFloat;
public GameObject healthyFood;
public GameObject unhealthyFood;
public GameObject notFood;
public Transform emptyObject;
void Start ()
{
StartGame ();
}
void Update ()
{
if (Input.GetKeyDown (KeyCode.LeftArrow)) {
print ("Left Choice");
StartGame ();
} else if (Input.GetKeyDown (KeyCode.RightArrow)) {
print ("Right Choice");
StartGame ();
}
}
void StartGame ()
{
randFloat = Random.Range (0, 70);
if (randFloat <= 40) {
Instantiate (healthyFood, emptyObject.position, emptyObject.rotation);
Debug.Log ("Healthy Food");
}
{
if (randFloat > 40 && randFloat <= 60) {
Instantiate (unhealthyFood, emptyObject.position, emptyObject.rotation);
Debug.Log ("Unhealthy Food");
}
{
if (randFloat > 60 && randFloat <= 70) {
Instantiate (notFood, emptyObject.position, emptyObject.rotation);
Debug.Log ("Not Food");
}
}
}
}
}
And here's the destroy script:
using UnityEngine;
using System.Collections;
public class DestroyedFood : MonoBehaviour
{
void Start ()
{
if (Input.GetKeyDown (KeyCode.LeftArrow)) {
Destroy (gameObject);
} else if (Input.GetKeyDown (KeyCode.RightArrow)) {
Destroy (gameObject);
}
}
}
Please help me out! Thanks! :)
↧
Instantiated GameObject's components are disabled
After I instantiated a Game Object (Sphere), it receives a new name (Sphere (Clone)) and all of its components are disabled except for the mesh renderer.
using UnityEngine;
using System.Collections;
public class CollisionAndResetSystem : MonoBehaviour {
int score = 0;
public GameObject Sphere;
public Transform sphere;
void OnCollisionEnter2D(Collision2D coll) {
if (coll.gameObject.tag == "Player") {
print ("hit");
Application.LoadLevel (0);
print(score);
}
if (coll.gameObject.tag == "Wall") {
print ("jumped over");
score++;
print(score);
Respawn ();
}
}
void Respawn(){ //Respawns the sphere
Destroy(gameObject);
Instantiate(Sphere, new Vector3(9, 1, 0), Quaternion.identity);
Sphere.name = "Sphere"; //Here is where i tried to fix the problem with the name "Sphere" turning into "Sphere(Clone)"
}
}
How do I go about instantiating Sphere while keeping all of its components activated, or rather activating its components in the script?
↧