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.
↧
Cloning objects infront of the player 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
↧
Candy Crush tutorial
Does anybody know where to find any good candy crush or bejeweled tutorials for unity are? I have been looking for a while and cant seem to find any good tutorials. I do not wish to purchase any packages from the asset store.
↧
↧
Random ball generator?
Hello,
I need help creating a game. I want to have a character on the bottom of the screen of my 2D game, and I want balls to be spawned randomly from the left and right walls. Now, everything is good so far, however I do not have any idea how to clone my already existing balls objects,randomly on the edge of the screen(right or left).
Any help?
Thank you!
↧
FLAPPY BIRD CLONE
So basically ive just started in unity and i found a tutorial to make a flappy bird clone (http://anwell.me/articles/unity3d-flappy-bird/) And basically my problem is when i downloaded the background to my textures folder and tried to add it to the scene it would show a circle with a across through it. Any answers appreciated. Thanks.
↧
Instatiating an object. Altering that new object causes prefab to be altered.
I am new to Unity3d and I'm playing around with a proof of concept project.
I'm currently stuck because I use a blank terrain prefab (easily instantiable) that I may want to include having its own scripts.
When my worldcreator object (blank object with script) starts instantiating the terrain pieces in a grid I'm noticing something very odd.
When I instantiate the terrain prefab, alter its height map and move on to instantiating the next piece, the next instantiating piece is carrying over heightmap terrain data from the previous instantiation. When I go to the unity3d editor and drag the prefab to the scene, it as well has the altered heightmap data from the last play.
I'm kind of lost as to why this would happen and I'm wondering if I'm not understanding what exactly instantiating really is or why the prefab in my project would be altered. Before today I thought prefabs were "read only" from a code perspective till they were instantiated and then altered based on in-game variables.
Here is my code.
#pragma strict
public var maxStrength: float = 1;
public var numOfTerrainBySide: int = 4;
public var terrainXsize = 500; //not used
public var terrainZsize = 500;
public var terrainYsize = 50;
public var terrainHeightMapSize = 512;
public var worldPiece: Terrain; //Prefab blank terrain linked from /prefabs/worldpiece
private var wploc : Vector3;
private var wprot : Quaternion;
function Start()
{
//get starting position of blank object "WorldCreator"
wploc = transform.position;
wprot = transform.rotation;
buildWorld();
}
function buildWorld()
{
//for each numOfTerrainBySide on X axis
for(var z = 1; z-1 < numOfTerrainBySide; z ++)
{
//for each numOfTerrainBySide on Z axis per X
for(var x = 1; x-1 < numOfTerrainBySide; x++)
{
var newloc = Vector3(terrainXsize * x - terrainXsize, wploc.y, terrainZsize * z - terrainZsize);
buildWorldPiece(newloc,wprot,x,z);
}
}
}
function buildWorldPiece(wploc,wprot,gridx,gridz)
{
//create terrain from prefab object
var newterrain : Terrain = new Instantiate(worldPiece, wploc, wprot);
//name object based on it's grid location
newterrain.name = "wp_" + gridx + "_" + gridz;
var xRes = newterrain.terrainData.heightmapWidth;
var yRes = newterrain.terrainData.heightmapHeight;
var heights = newterrain.terrainData.GetHeights(0, 0, xRes, yRes);
for (var x: int = 0; x < yRes; x++)
{
for (var z: int = 0; z < xRes; z++)
{
//proof of concept to put border around edges of multiple terrains
if (gridx == 1 && z == 0)
{
heights[x,z] = Random.Range(1.0f, terrainYsize);
}
if (gridz == 1 && x == 0)
{
heights[x,z] = Random.Range(1.0f, terrainYsize);
}
if (gridx == numOfTerrainBySide && z == terrainHeightMapSize)
{
heights[x,z] = Random.Range(1.0f, terrainYsize);
}
if (gridz == numOfTerrainBySide && x == terrainHeightMapSize)
{
heights[x,z] = Random.Range(1.0f, terrainYsize);
}
}
}
newterrain.terrainData.SetHeights(0, 0, heights);
}
↧
Following Object can't find newly Instantiated Object (Solved)
I have 2 objects in my game, a sphere and a cube. The sphere starts at position A and the cube moves towards it using the following script -
#pragma strict
public var victim : Transform;
private var navComponent : NavMeshAgent;
function Start()
{
navComponent = this.transform.GetComponent(NavMeshAgent);
}
function Update()
{
if(victim)
{
navComponent.SetDestination(victim.position);
}
}
The sphere has a script on it that allows it to be destroyed and instantiated at a new location -
#pragma strict
public var resourceSpawnPoints : Transform[]; //Makes a list of transforms in my game
public var randomPos : int; //This denotes that the variable randomNum will be a whole number
public var resourceType : GameObject;
function OnTriggerEnter(thing: Collider)
{
if (thing.tag == "Harvester")
{
ResourceRespawn();
}
}
function ResourceRespawn()
{
randomPos = Random.Range(0,4); // generates random number between 0 and 3.
transform.position = resourceSpawnPoints[randomPos].transform.position;
//Assigns the number generated in the previous line to the 'spawnPoints' variable
//Which then dictates which spawnPoint(location) is used (spawnPoint1, spawnPoint2, spawnPoint3)
Instantiate(resourceType, resourceSpawnPoints[randomPos].position, resourceSpawnPoints[randomPos].rotation);
Destroy (gameObject);
}
My problem is that once the cube/harvester reaches the sphere it activates the sphere's destroy/instantiate script but then stops. It doesn't then move towards the newly instantiated sphere.
Any suggestions as to why this happens (or doesn't happen to be more precise)
???
↧
↧
anim.SetBool not working on cloned GameObjects
Hey, new to Unity2D. I currently working on creating a 2D sidescroller game. I am cloning an enemy in my game that when it take a hit it should set a boolean to true. The issue is that it will change the expression on the original object but not the the clone. Below is the script attached to the original object.
using UnityEngine;
using System.Collections;
public class EnemyScript : MonoBehaviour {
public Transform sightStart, sightEnd, target;
public bool spotted=false;
public bool facingLeft= true;
public HealthScript character;
public ScoreScript characterA;
public Transform zombie;
public float velocity=2f;
RaycastHit2D WhatIHit;
public bool InRange;
Animator anim;
int EcurrentHealth =2;
void Start(){
anim = GetComponent ();
}
// Update is called once per frame
void FixedUpdate () {
Raycasting ();
}
void Raycasting(){
spotted = Physics2D.Linecast (sightStart.position, sightEnd.position, 1 << LayerMask.NameToLayer ("Player"));
if (spotted == true ) {
anim.SetBool ("Spotted",true);
} else {
anim.SetBool ("Spotted",false);
}
facingLeft = !facingLeft;
if (target.position.x < zombie.position.x) {
transform.eulerAngles = new Vector2 (0, 180);
rigidbody2D.velocity = new Vector2 (velocity * -1, rigidbody2D.velocity.y);// enemy is walks to the left
} else {
transform.eulerAngles = new Vector2 (0, 0);
rigidbody2D.velocity = new Vector2 (velocity, rigidbody2D.velocity.y);// enemy moving to the right
}
if (Physics2D.Linecast (sightStart.position, sightEnd.position, 1 << LayerMask.NameToLayer ("Player"))) {
WhatIHit = Physics2D.Linecast (sightStart.position, sightEnd.position, 1 << LayerMask.NameToLayer ("Player"));
InRange = true;
}
else
{
WhatIHit = Physics2D.Linecast (sightStart.position, sightEnd.position, 1 << LayerMask.NameToLayer ("Player"));
InRange=false;
}
}
void AttackPlayer(){
StartCoroutine (WaitSet ());
if (InRange == true)
{
character.ApplyDamage(1);
}
}
IEnumerator WaitSet(){
yield return new WaitForSeconds (1);
}
public void EnemyDamage (int enemyhit){
anim.SetBool ("IwasHit",true);
EcurrentHealth = EcurrentHealth - enemyhit;
if (EcurrentHealth <= 0) {
Destroy(GameObject.Find("ZombieA(Clone)"));
}
}
}
↧
Rotate a cloned object with key press
I'm trying to rotate a cloned object once it is spawned but i'm having difficulty and cant find any information about how to do this.
For example, i spawn a wall, once i press "R" it rotates to 90 degrees along its x axis. Or, if you press "R" it transforms to 90 and then you put it down? I just need an understanding on how to do this. I'm unfamiliar with Quaternions is this the problem?? The code i have doesn't seem to be working.
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
// Storage point for the Ray
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
// Assigning the point its variable
endPoint = hit.point;
GameObject clone;
// Clone the objects and spawn them in the game 'world'
clone = Instantiate(items[i], endPoint, items[i].transform.rotation) as GameObject;
if (Input.GetKey(KeyCode.R))
{
clone.transform.Rotate(0, 90, 0);
Debug.Log("Rotating Object");
}
}
}
↧
Why could I delete my clones onlY in the same order of instantiation?
Hi! I am kind of new to Unity.
So, I've been trying to destroy set of clones on mouse click instantiated during my game play.
My code for instantiation goes like this.
public class inst : MonoBehaviour {
public GameObject ch;
public Transform[] spawnpoint=new Transform[3]; // Use this for initialization
void Start () {
spwn();
}
void spwn(){
for (int i=0; i<4; i++) {
Vector3 spawnVector = new Vector3 (spawnpoint[i].position.x, spawnpoint[i].position.y, spawnpoint[i].position.z);
Instantiate (ch , spawnVector, spawnpoint[i].rotation);
}
}
// Update is called once per frame
void Update () {
}
}
And, I have a separate code for destroying the clones on Mouse click which is added to the respective prefab.
But when I am trying to destroy them, they are getting destroyed in the same order in which they
are created.
For eg., if I am clicking on my clone in spawnpoint[2] transform, spawnpoint[0] clone is getting destroyed. And on a second click of the same spawnpoint[1[]'s transform is being destroyed.
Please help me in making my code work properly. Thanks in advance :)
p.s.: I might have misunderstood and would have something wrong. I am just a beginner. In that case please correct me.
↧
Creating clones
Could someone help me with my problem - i got script which makes a clone of particles after casting it
#pragma strict
private var ray : Ray;
private var hit : RaycastHit;
var particles : Transform;
function Start () {
}
var speed = 20;
var time=2.0;
function Update () {
time = time + Time.deltaTime;
if (Input.GetMouseButtonUp(1)&&time>=2.0) {
time=0.0;
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, hit)){
transform.position.x = hit.point.x;
transform.position.z = hit.point.z;
Instantiate (particles, transform.position, transform.rotation);
}
}
}
- this script making clone called "teleport(clone)" - how can i destroy this clone after casting
- i tried scripts with Destroy(); but it doesnt work for me
Sorry for bad english
↧
↧
Application.LoadLevel object clone spam
Hi, I tried DontDestroyOnLoad and Application.LoadLevel and the object is constantly created in the second level. Why is this?
using UnityEngine;
using System.Collections;
public class BacktrackingTest : MonoBehaviour
{
public float float1 = 420;
public float float2 = 9000;
private bool LevelLoaded = false;
void Start ()
{
DontDestroyOnLoad(gameObject);
//Data transfer between unity scenes test, does it subtract twice?
float2 = float2 - float1;
}
void FixedUpdate ()
{
if(Time.time>5 && LevelLoaded==false)
{
Application.LoadLevel(1);
LevelLoaded=true;
}
}
}
↧
control clone objects by buttons
hi, sorry for my english.
i have a gun on the left of screen. i can instantiate bullet end of its with Input.GetMouseButtonUp(0) and i destroy the bullet in 7 second. i want to move the clone bullets by left and right button. the problem is i dont know how to do that. i can move objects but clone objects doesnt affect.
here is my instantiate code attached to gun
#pragma strict
var readynow : boolean = true;
var gun : Transform;
public var bulletPrefab : Rigidbody;
public var gunEnd : Transform;
public var mouse_pos = Input.mousePosition;
function Update() {
if (Input.GetMouseButtonUp(0)) {
if(readynow){
Kopyala();
}
}
}
function Kopyala() {
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
var hit: RaycastHit;
yield WaitForSeconds(0.1);
if (Physics.Raycast(ray, hit)) {
var bulletInstance : Rigidbody;
bulletInstance = Instantiate(bulletPrefab, gunEnd.position, gunEnd.rotation);
bulletInstance.transform.forward = gun.forward;
bulletInstance.rigidbody.AddForce(bulletInstance.transform.forward * 650);
}
}
and here is movement script attached bullet prefab
#pragma strict
function Start () {
}
function Update ()
{
{
Destroy(gameObject,7);
}
}
public function FixedUpdate ()
{
if(Input.GetButton("Fire1"))
{
rigidbody.AddForce (10, 20, 0);
}
if(Input.GetButton("Fire2"))
{
rigidbody.AddForce (-10, 20, 0);
}
}
as you can see i can add force clone bullets by mouse right and left clicks.
how convert mouse right and left buttons to UI buttons. please help
↧
When cloning, how do you make your clones keep the original properties?
Hello,
I am trying to clone an object, and I want the clone to have the same velocity as the original object, but every time I try, the clone is not keeping the original velocity. How can I solve this?
Thank you for your responses!
↧