In my attempt to make an RTS game I have created a node system. Each node has a different node number so that way specific units know which one to go to. There is one original node(Goto) and then when the player right clicks a new node(NewGoto) is spawned. There is one serious problem though, the node numbers always stay at 1. Here is the code so I can explain more:
cloneScript = originalgoto.gameObject.GetComponent(NodePlacement);
originalgoto = Instantiate(newgoto, transform.position, transform.rotation);
cloneScript.nodeNum = nodeNum + 1;
nodeNum = nodeNum + 1;
originalgoto = newgoto;
I have been trying to base the node number off of the previous node number from the previous clone. All the nodes use the same script. To accomplish that I tried
originalgoto = newgoto;
but that did not work, and I am not sure what to do as I have not been able to find the answer. Any feedback is appreciated. Also if I did not explain well enough feel free to ask questions.
↧
Clone Instantiated from another Clone.
↧
Instantiated Component not Cloning Parent Classes?
When I call `MyComponent c = Instantiate( MyComponent ) as MyComponent;` it does not clone **any** of the values inside of MyComponent's parent classes.
To clarify, I have my class order structure set up like this:
BaseClass--------------------------------------------------->Top Level Class
MonoBehaviour->MyBaseClass->MyMiddleClass->MyComponent
So, none of the variables from MyBaseClass or MyMiddleClass are being carried over when doing an Instantiate on the top level `MyComponent` class (aka, my component that is exposed in the Inspector).
Does anyone know if this is expected Unity behavior? For example, I know that Unity does not ever expose parent class's public variables in the inspector (and this seems to be by design).
↧
↧
Prefab clones behaviour
Hello everyone,
I don't get how prefab instantiation works.
I'm coding a 2d vertical infinite scrolling and I made a script that continually create new tiles of background (prefab) at top and destroy itself when its at bottom.
Then each background instantiate a group of windows (prefab too). Later some window would be animated or scripted or whatever so it is important that each window is a different gameObject.
The problem is, each background seems to herit windows from the last background created. So 1st bacnkground has 3 windows, 2nd has 6, 3rd has 9... etc..
![alt text][1]
like if all child were cloned too... but they dont exist in the prefab, I create them at runtime..
I'm sure I'm not using those prefabs the good way but that is my first Unity Project I don't how to handle the all-situation so if you have any clue..
here's my code :
using UnityEngine;
using System.Collections;
public class bg_parallax : MonoBehaviour
{
static public Vector2 speed = new Vector2 (5, 5);
static public Vector2 direction = new Vector2 (0, -1);
public GameObject background;
public GameObject window;
private bool needChild = true;
// Use this for initialization
void Start ()
{
((GameObject)Instantiate (window, new Vector3 (-1.8f, -1.5f, 19f), transform.rotation)).transform.parent = transform;
((GameObject)Instantiate (window, new Vector3 (0f, -1.5f, 19f), transform.rotation)).transform.parent = transform;
((GameObject)Instantiate (window, new Vector3 (1.8f, -1.5f, 19f), transform.rotation)).transform.parent = transform;
}
// Update is called once per frame
void Update ()
{
}
void FixedUpdate ()
{
transform.Translate (new Vector3 (speed.x * direction.x, speed.y * direction.y, 0) * Time.deltaTime);
if (needChild && transform.position.y <= 0) {
((GameObject)Instantiate (background, new Vector3 (0, transform.position.y + renderer.bounds.size.y, 20), transform.rotation)).transform.parent = transform.parent;
needChild = false;
}
if (transform.position.y <= renderer.bounds.size.y * -1)
{
for(int i = 0; i < transform.childCount; i++)
DestroyImmediate(transform.GetChild(i).gameObject);
Destroy (gameObject);
}
}
}
[1]: /storage/temp/29153-screen+shot+2014-07-13+at+15.28.37.png
↧
Clone Selector
Hi unityAnswer's Users!
I need help about question of clone.
I have a script that generates a new clone every time you touch an object.
Can I do, with a script, to assign each of these clones a different value of the same variable?
thanks!!
↧
problem with yield WaitForSeconds()
I want to spawn a prefab after 2 seconds but I am having an issue with my yield function, here is the code:
using UnityEngine;
using System.Collections;
public class spawn : MonoBehaviour
{
// Prefab to spawn
public int distance = 10;
public int timeDelay = 5;
public float speed = 0.1f;
public Transform clone;
public GameObject spawnPoint;
// Use this for initialization
void Start()
{
}
void Update()
{
transform.position += transform.forward * distance * speed;
while (true)
{
//My yield is showing up in red giving me an error
yield WaitForSeconds(timeDelay);
Instantiate (clone, spawnPoint.transform.position, spawnPoint.transform.rotation);
}
}
}
This is what the console returns:
![alt text][1]
Am i doing something wrong here?
[1]: /storage/temp/29350-capture.png
↧
↧
Odd cloning error.
This script is having an odd issue, When I try to clone it, It gives me [Running C#]:
! Assetss/Cloning.cs(11,29): error CS1525: Unexpected symbol 'clone'
Here is my code:
using UnityEngine;
using System.Collections;
public class Cloning : MonoBehaviour {
// Update is called once per frame
void Update () {
var rndizer = Random.Range (1, 11);
if (rndizer == 1) {
Rigidbody clone;
clone = Instantiate(GameObject.find("mainEnemy"), transform.position, transform.rotation) as Rigidbody
clone.velocity = transform.TransformDirection(Vector3.forward * 4);
}
}
}
↧
Pass a copy of a GameObject as variable to another script?
Hello...
I'm trying to set up a teleport system that destroys the original object and then spawns a clone of that object at the exit portal.
I don't want to just instantiate a prefab, as I want to keep changes to the object that happen during gameplay, and I don't want to simply move the object, because I have a spawner object that has a few useful functions like a delay and clearing the area of obstructions, etc.
I want to pass the object in its current state as a variable, destroy the original, then have the spawner instantiate a clone after a delay.
However, I'm getting the error: "MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object."
Here is the code for my warp entrance object:
#pragma strict
var on : boolean = true;
var teleportTarget : GameObject;
var ballSpawn : GameObject;
var yieldBefore : float = 00;
var yieldAfter : float = 00;
var preserveVelocity : boolean = true;
var holdDuringDelay : boolean = true;
var affectTag : String = "Ball";
private var teleporting : boolean = false;
private var teleportedObject : GameObject;
private var initialPosition : Vector3;
private var incomingVelocity : Vector3;
function Start ()
{
}
function Update ()
{
if (teleporting && holdDuringDelay)
{
teleportedObject.transform.position = initialPosition;
}
}
function OnTriggerEnter(objectCollision : Collider)
{
if ((objectCollision.gameObject.tag == affectTag) && (teleportedObject != objectCollision.gameObject) && (on))
{
initialPosition = objectCollision.gameObject.transform.position;
incomingVelocity = objectCollision.gameObject.rigidbody.velocity;
teleport(objectCollision.gameObject);
}
}
function teleport(object : GameObject)
{
teleporting = true;
teleportedObject = object;
yield WaitForSeconds(yieldBefore);
var instantiatedObject = Instantiate(ballSpawn, teleportTarget.transform.position, teleportTarget.transform.rotation);
if (instantiatedObject.GetComponentInChildren(BallSpawn))
{
instantiatedObject.GetComponentInChildren(BallSpawn).spawnOnStart = true;
instantiatedObject.GetComponentInChildren(BallSpawn).ball = teleportedObject;
instantiatedObject.GetComponentInChildren(BallSpawn).spawnDelay = this.yieldAfter;
instantiatedObject.GetComponentInChildren(BallSpawn).destroyAfterSpawn = true;
if (preserveVelocity)
{
instantiatedObject.GetComponentInChildren(BallSpawn).spawnWithVelocity = this.incomingVelocity;
}
}
teleportedObject = null;
teleporting = false;
DestroyOriginal(object);
}
function DestroyOriginal(object : GameObject)
{
Destroy(object);
}
Thanks in advance, smart people.
↧
How to Clone Array1 into Array2 in Unity? Using JavaScript.
I'm new in Unity, someone can help..?
I want to Create a clone from Array1 to Array2. And do what I want in Array2 without affecting the Array1.
<---something like this--->
var TextArray1 = ["sample1", "sample2"];
var TextArray2;
<------------------------->
↧
What is a good way to instantiate new prefabs via script?
I'm working on a prototype for a tree sim game. The tree is made up of multiple pieces and right now, I want a new piece to appear when I click an existing piece. The new piece's scale, location, and rotation are based on the piece that was clicked. The pieces are based on a TreePiece prefab. I tried creating a Transform variable in the TreePiece's script and assigning the TreePiece prefab in the editor. In script, I used Instantiate to create a new piece. The problem is, each new piece's name adds an extra (clone) to the end (for example: TreePiece(clone)(clone)(clone) ) and weird things are happening like existing pieces re-sizing when I try to resize new pieces. I'm certain this is due to the way I'm trying Insantiate new pieces.
Can someone explain why this might be happening? Is their a better way to instantiate new prefabs via script? Each piece needs to be able to create new pieces and more code will be added to them later as I build the game.
By the way, I'm fairly new to Unity.
Thanks a lot!
↧
↧
"Ghost" instance of a prefab
This is brand new to me. An extra instance of my prefab randomly instantiates itself out of the blue at runtime, appearing nowhere in the hierarchy. Yet, Double-clicking it does bring it in focus in the inspector, in which it only has one component out of a bunch and everything is greyed out. Sometimes it doesn't happen, but once it does, it keeps on consistently happening until I restart the editor, in which case it stops happening for a little while. It generally causes one extra instance to appear, but one case had it spawn exactly fifty times.
If that's of any relevance, one of my scripts declares an array of GameObjects like so.
GameObject[] others = new GameObject[all.Length-1];
![Circled in red is the array.][1]
[1]: /storage/temp/29808-phantomclone.png
↧
Assign components to Clone objects
I have a Camera object that needs to follow my player (to create a Mini Map).
I'm using code from the Photon Viki Demo to spawn players,
and it what it does is it creates clones in the Hierarchy ex: Charpref(Clone)10001, Charpref(Clone)40222 and etc... for each player.
How can I get the Mini Map to have each clone as a Target?
**Code from the Photon Viking Demo (in the Asset Store).**
void StartGame()
{
Camera.main.farClipPlane = 100; //Main menu set this to 0.4 for a nicer BG
//prepare instantiation data for the viking: Randomly diable the axe and/or shield
bool[] enabledRenderers = new bool[2];
enabledRenderers[0] = Random.Range(0,2)==0;//Axe
enabledRenderers[1] = Random.Range(0, 2) == 0; ;//Shield
object[] objs = new object[1]; // Put our bool data in an object array, to send
objs[0] = enabledRenderers;
// Spawn our local player
PhotonNetwork.Instantiate(this.playerPrefabName, transform.position, Quaternion.identity, 0, objs);
}
**And here is the "Mini map"** :
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
public Transform Target;
void LateUpdate () {
transform.position = new Vector3 (Target.position.x, transform.position.y, Target.position.z);
}
}
**Edit:** I was thinking of possible tagging the Charpref with "Player" and making the Mini Map respond to anything with that tag attached, yet that still didn't work though.
↧
how do you to resolve this unity message
Can´t add component "rigidbody", game object is generatede prefab and only be modified through an assetpostproccesor.
↧
Cloning objects infront of the player at a random distance
Hello there, First I want to thank everyone who helped me last time :)
Now I have one more question, Script is:
using UnityEngine; using System.Collections;
public class GameController : MonoBehaviour {
///
/// The flasica.
///
public Transform flasica;
private float maxHigh;
public GameObject[] gameObjectSet;
void Start () {
Vector3 targetHigh = new Vector3 (-8.5f, -5.0f, 0.0f);
float flasicaHigh = flasica.renderer.bounds.extents.x;
maxHigh= targetHigh.x - flasicaHigh;
StartCoroutine (Spawn ());
}
IEnumerator Spawn () {
yield return new WaitForSeconds (2.0f);
while (true) {
Vector3 spawnPosition = new Vector3 (
Random.Range (-maxHigh, maxHigh),
transform.position.y,
0.0f
);
int whichItem = Random.Range (0, 5);
Quaternion spawnRotation = Quaternion.identity;
Instantiate ((gameObjectSet [whichItem]), spawnPosition, spawnRotation);
yield return new WaitForSeconds (Random.Range (1.0f,2.5f));
}
}
}
Now i need help, how can I create script so that clone objects will be showing up infront of player? I need clone to be Directly in front at a random distance.
↧
↧
Minecraft - Water Physics
Hello!
I'm making a minecraft clone and I want to create some water too!
I made a script that checks whether an object exists next to the water object and if there's no object there, it creates another water object which does the same thing. So it's like a loop. The problem is that it doesn't creates the water object from all of it sides when there's no object there. What's the problem?
Here's the script:
var waterObj : Transform;
var hit : RaycastHit;
var distance : float = 1.0;
function Update() {
if(Physics.Raycast(transform.position,Vector3(transform.position.x+1,transform.position.y,transform.position.z),hit,distance)) {
return;
} else {
Instantiate(waterObj,Vector3(transform.position.x+1,transform.position.y,transform.position.z),Quaternion.identity);
}
if(Physics.Raycast(transform.position,Vector3(transform.position.x-1,transform.position.y,transform.position.z),hit,distance)) {
return;
} else {
Instantiate(waterObj,Vector3(transform.position.x-1,transform.position.y,transform.position.z),Quaternion.identity);
}
if(Physics.Raycast(transform.position,Vector3(transform.position.x,transform.position.y,transform.position.z+1),hit,distance)) {
return;
} else {
Instantiate(waterObj,Vector3(transform.position.x,transform.position.y,transform.position.z+1),Quaternion.identity);
}
if(Physics.Raycast(transform.position,Vector3(transform.position.x,transform.position.y,transform.position.z-1),hit,distance)) {
return;
} else {
Instantiate(waterObj,Vector3(transform.position.x,transform.position.y,transform.position.z-1),Quaternion.identity);
}
if(Physics.Raycast(transform.position,Vector3(transform.position.x,transform.position.y-1,transform.position.z),hit,distance)) {
return;
} else {
Instantiate(waterObj,Vector3(transform.position.x,transform.position.y-1,transform.position.z),Quaternion.identity);
}
}
↧
Pausing animation/movement of a Clone (instantiated enemy)
I'm trying to implement a simple pause button and have been able to pause all animations and motions of my various characters in the game except the clones.
I instantiate enemies a few seconds after loading level and they produce clones with names like "Orc_Mage(Clone)", etc.
I define the transform ...
private var orc_pikeman_Clone : Transform;
To find the game objects to "pause" I do this:
orc_pikeman_Clone = GameObject.Find("orc_pikeman(Clone)").transform;
Then I try to pause it's animations with this:
orc_pikeman_Clone.SendMessage("buttonPauseHandler", 0);
the enemy doesn't pause.
I should add what buttonPauseHandler does ...
function buttonPauseHandler()
{
Debug.Log( "buttonPauseHandler - EnemyOcrPikeman");
animation.enabled=false;
movementBeforePause.x = movement.x;
movementBeforePause.y = movement.y;
movementBeforePause.z = movement.z;
movement.x = 0.0f;
movement.y = 0.0f;
movement.z = 0.0f;
}
Do you have to do something special to pause the animation of a instantiated clone?
Thanks!
↧
How can I enable/disable a component of a Clone
So I am working on a game which spawns between 0 and 12 clones of a prefab, what I wanted to do at first was to enable the component on a set amount of those clones but I couldn't figure out how to do that, what I am trying to do at the moment is enable that component if a condition is reached but if I use `gameobject.GetComponent().enabled = true;` it has no effect on the prefab and the component is still disabled.
If there is another way of going about this please let me know as I really need to get it working.
↧
How do I change the transform of a clone object
I'm trying to change the transform of an object I've just instantiated using the following:
public GameObject marker;
public float maxLength;
newVector = Vector2.ClampMagnitude(diffVector, maxLength);
Instantiate(marker, newVector, transform.rotation);
newVector = Vector2.ClampMagnitude(diffVector, maxLength);
marker.gameObject.transform.position = newVector;
Debug.Log("Marker position = " + marker.gameObject.transform.position);
The diffVector is the difference between two objects that I want to track. There is other code around each block above but these are the pertinent parts.
I use the Debug.log to see that the marker.gameObject.position.transform is changing correctly, but the actual game object marker(clone) isn't.
My guess is because its a clone but I don't know how to reference them in the script.
Any help would be appreciated.
↧
↧
Having an issue with instantiating objects on button clicks
Theres a button in my scene and I want to instantiate an object when I press it but it returns the error:
Type IPointerClickHandler expected Button received. i:0. The variable bullet of helicopter has not been assigned.
You probably need to assign the missile variable of the helicopter script in the inspector
public Rigidbody bullet;
public void fire()
{
Rigidbody clone;
clone = Instantiate(bullet, transform.position, transform.rotation) as Rigidbody;
clone.velocity = transform.TransformDirection(Vector3.forward * 10);
}
I have the bullet prefab on my object in the inspector and my button uses the function above when clicked so I don't know what the problem is, if anyone could help, I'd appreciate it
↧
send SCORE from OBJECT(clone) to other file
Hi guys. My experience is very small. And my english bad.
And Google in 10 hours could not help me.
I have 3 script
1. cameraController
2. bg
3. bubbleMove
cameraController contains a system of points.
bg creates object clones from prefab, prefab have script bubbleMove, and when the condition inside the script right, points in cameraController must be plus, but unity3d say me:
"**NullReferenceException: Object reference not set to an instance of an object
bubbleMove.Update () (at Assets/bubbleMove.cs:18)**".
What am I doing wrong? How to deal?
I'm attach the screens and scripts.
**cameraController**
using UnityEngine;
using System.Collections;
public class cameraController : MonoBehaviour {
public bubbleMove bubbleMove;
public Vector3 mousPos;
public Vector3 mousePos;
public Vector3 worldPos;
public int width;
public int height;
public Vector2 screenSize;
public Vector2 worldScreenSize;
public int score = 0;
public int scorePlus = 1;
// Use this for initialization
void Start () {
screenSize = new Vector2(width, height);
worldScreenSize = Camera.main.ScreenToWorldPoint(screenSize);
score = 0;
scorePlus = 1;
width = Screen.width;
height = Screen.height;
}
// Update is called once per frame
void Update () {
print("scoreFrom cameraController="+score);
}
}
**bg**
using UnityEngine;
using System.Collections;
public class bg : MonoBehaviour {
public cameraController cameraController;
public GameObject RandB;
public int bubbleCount;
float d;
private int i;
private Vector2 mapSize;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
mapSize = new Vector2(cameraController.worldScreenSize.x, cameraController.worldScreenSize.y);
for (int i = 0; d + 1 < Time.time && i < bubbleCount; i++ )
{
GameObject bubbleClone1;
bubbleClone1 = Instantiate(RandB, new Vector2(Random.Range(-mapSize.x, mapSize.x),
Random.Range(-mapSize.y, mapSize.y)), RandB.transform.rotation) as GameObject;
GameObject bubbleClone2;
bubbleClone2 = Instantiate(RandB, new Vector2(Random.Range(-mapSize.x, mapSize.x),
Random.Range(-mapSize.y, mapSize.y)), RandB.transform.rotation) as GameObject;
GameObject bubbleClone3;
bubbleClone3 = Instantiate(RandB, new Vector2(Random.Range(-mapSize.x, mapSize.x),
Random.Range(-mapSize.y, mapSize.y)), RandB.transform.rotation) as GameObject;
GameObject bubbleClone4;
bubbleClone4 = Instantiate(RandB, new Vector2(Random.Range(-mapSize.x, mapSize.x),
Random.Range(-mapSize.y, mapSize.y)), RandB.transform.rotation) as GameObject;
d = Time.time;
}
}
}
**bubbleMove**
using UnityEngine;
using System.Collections;
public class bubbleMove : MonoBehaviour {
public cameraController cameraController;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
transform.Translate (-Vector3.up * 0.1001f);
if(transform.position.y < 0)
{
cameraController.score = cameraController.score + cameraController.scorePlus;
print("score from bubbleMove="+cameraController.score);
Destroy (gameObject);
}
}
}
![alt text][1]
![alt text][2]
[1]: /storage/temp/33010-myunity.png
[2]: /storage/temp/33012-errorunity.png
↧
Reference an Instance of an Object?C#
Hi there! I've got a question about a specific problem related to a topic which seems to be hard to understand.
That topic is .GetComponent<>();
The question may sound silly but before I got overwhelmed by errors I thought I learned [this][1] lesson well... but now I don't know what to think anymore!
**And the question is:**
**What do I have to do to access/reference/manipulate an instantiated prefab/GameObject/thing?**
Now something more specific ( i'm keeping this generic enough so that any answer may easily be understood by others in my same needs):
I've got scriptA attached to objectA, scriptB attached to objectB and scriptC attached to objectA. scriptA has a public "slot" in the editor in which i put objectB. This is a simple way to reference another GameObject.
Then I put my objectA with its two scripts inside the Hierarchy, so that it exists.
*When I execute in scriptA an Instantiate(objectB) I'm making a Clone of that GameObject, am I right? But what if my scriptC tried to access a variable of scriptB?*
*I've set up the references "properly", and by properly I mean that I followed the .GetComponent<>(); method. Obviously I get a null reference exception in this case.*
*I know that exception is right, it does make sense: the hierarchy contains no objectB so there's not a scriptB either. But the Hierarchy do contains an objectB(Clone), which has a scriptB.*
**So what would I have to do to "talk" to that Clone with my scriptC?**
I also tried the static workaround, even if it's not smart when you have multiple clones on screen. It didn't worked.
*The only thing I managed to do to solve this issue is to put objectB inside the Hierarchy too, thus disabling the Instantiate execution inside scriptA of objectA. This way I just have to make a regular Find & GetComponent with scriptC to access stuff in scriptB. But this is not what I wanted in the first place.*
My apologies, I know this argument has been already explained in tons of examples, but I just couldn't get it.
Needless to say that a link or some lines of code would be very appreciated.
Thanks in advance for your kindness.
P.S.: I can provide you my own code if you think that might improve your answers, but it's just a coded version of what I stated above.
[1]: http://answers.unity3d.com/questions/550578/cant-understand-getcomponent-c.html
↧