Hi!
I am making a simple player follow script and it is not working. When I checked what it is finding, it is finding "Player(Clone)". There is no clone in the scene or in the prefabs. Why is it doing this?
My code.
using UnityEngine;
using System.Collections;
public class CameraFollow : MonoBehaviour {
public GameObject target;
void Start(){
target = GameObject.FindGameObjectWithTag("Player");
}
void Update(){
transform.position = new Vector3(target.transform.position.x, target.transform.position.y, -10);
}
}
↧
Script finding a none-existing player clone
↧
multiple objects with same tag not recognized
im making a game where by if the player drops a object to house he scores a point. i have done it so that when the object touchs a collider on the house the object is destoryed and then the point get appended by one. how ever i have several houses all with the same tag so when i use the following code nothing happens.. help
public Despawn_Objects ScoreFromSnow;
//public Despawn_Objects ScoreFrom1;
public int points;
// Use this for initialization
void Start () {
GetComponent (); //get the script despawn_objects
}
// Update is called once per frame
void Update () {
GameObject colliderSnow = GameObject.FindGameObjectsWithTag ("scorer")[0];
ScoreFromSnow = colliderSnow.GetComponent ();
if(ScoreFromSnow.gone==true){
ScoreFromSnow.gone=false;
points++;
guiText.text = points.ToString ();
}
}
}
the code only works when i have only one object with tag "scorer" any more than that and nothing works.
↧
↧
Unexpected Symbol :
Hey All,
So, in the GameController script I instantiate 1 posse leader and 10 members who I all give a posse value (int). In a script for posse members I want to check if the posseleader is still in the scene and if not, reset the posse-value of the members to 0.
This is my script:
using UnityEngine;
using System.Collections;
public class Posse : MonoBehaviour {
public int posse;
public GameController gameController;
public PosseLeader posseLeader;
// Use this for initialization
void Start ()
{
GameObject gameControllerObject = GameObject.FindWithTag ("GameController");
if (gameControllerObject != null)
{
gameController = gameControllerObject.GetComponent ();
}
if (gameControllerObject == null)
{
Debug.Log ("Cannot find GameController");
}
posse = gameController.posse;
}
// Update is called once per frame
void Update () {
var leader : GameObject[];
leader = GameObject.FindGameObjectsWithTag("enemy");
if (leader.length == 0) {
posse = 0;
}
if (leader.length != 0) {
for (int y=0; y <= leader.length; y++) {
GameObject posseLeaderObject = leader[y];
posseLeader = posseLeaderObject.GetComponent ();
if (posseLeader.posse = posse){
posse = 0;
}
}
}
}
}
However, I get:
Assets/Scripts/Posse.cs(29,28): error CS1525: Unexpected symbol `:', expecting `)', `,', `;', `[', or `='
For the ':' behind var leader. What am I doing wrong here? I took a snippet from: http://docs.unity3d.com/ScriptReference/GameObject.FindGameObjectsWithTag.html
And, by any change, is the code after this correct / possible? Or should I tackle this problem differently?
Thanks in advance, it is just my first week in Unity so apologies for the level of my question.
↧
GameObject.FindGameObjectsWithTag still finding destroyed object (C#)
I have a few methods that perform some tasks. Some are stored publicly on my "Manager" that always exists. My levels have a "Level_Manager" that call them as needed.
When I try the following I get incorrect results.
character_spawn_manager_inst.DestroyLevel (); //first level has 1 spawn
character_spawn_manager_inst.LoadLevel (); //new level has 4 spawns
character_spawn_manager_inst.SpawnFinder();
result: 5 spawns?
Here is the main code of SpawnFinder:
spawnPoints = new GameObject[GameObject.FindGameObjectsWithTag ("Spawn_Point").Length];
spawnPoints = GameObject.FindGameObjectsWithTag ("Spawn_Point");
Why is GameObject.FindGameObjectsWithTag still finding the recently destroyed objects?
I'm guessing the reasoning is something simple that I'm just not seeing. Any input would be great. Thanks!
↧
Accesing components on multiple objects in c#?
Hi there.
**What I'm trying to do is to have triggers in the scene that will allow the player to rotate the camera around him, only when he is inside one of those objects colliders.**
I have multiple object that all have the same script attached (in this instance named RotateArea.cs).
And I want to access all those objects from another objects script component (CameraRotator.cs).
Is there a way in Unity to access all of those at the same time? I'm currently using FindGameObjectWithTag, as it gets an error as soon as I use FindGameObjectsWithTag. Appearently I can't use .GetComponent after a FindGameObjectsWithTag.
What to do?
**CameraRotator**
using UnityEngine;
using System.Collections;
public class CameraRotator : MonoBehaviour
{
public float rotateTime = 1.0f;
private bool _isTweening = false;
private CrunchPlatformColliders _cruncher;
private DisablePlayer _disablePlayer;
RotateArea rotateFunction;
void Start ()
{
_cruncher = GetComponentInChildren();
GameObject player = GameObject.FindGameObjectWithTag("Player");
_disablePlayer = player.GetComponentInChildren();
rotateFunction = GameObject.FindGameObjectWithTag("rotateZone").GetComponent();
}
void Update(){
if(rotateFunction.isInRotateZone)
{
if (Input.GetKeyDown(KeyCode.Z))
{
rotateTween(90);
}
if (Input.GetKeyDown(KeyCode.X))
{
rotateTween(-90);
}
}
}
private void rotateTween(float amount)
{
if (_isTweening == false)
{
_isTweening = true;
// _cruncher.setPlayerPos();
_disablePlayer.disable();
Vector3 rot = new Vector3(0,amount, 0);
iTween.RotateAdd(gameObject, iTween.Hash(iT.RotateAdd.time, rotateTime, iT.RotateAdd.amount, rot, iT.RotateAdd.easetype, iTween.EaseType.easeInOutSine, iT.RotateAdd.oncomplete, "onColorTweenComplete"));
}
}
private void onColorTweenComplete()
{
_isTweening = false;
_disablePlayer.enable();
_cruncher = GetComponentInChildren();
//_cruncher.crunchCollidersToPlayer();
}
}
**RotateArea**
using UnityEngine;
using System.Collections;
public class RotateArea : MonoBehaviour {
public bool isInRotateZone = false;
public GUIText referencetotext;
// Use this for initialization
void OnTriggerEnter ()
{
isInRotateZone = true;
referencetotext.text ="Press Z or X to change lane";
}
void OnTriggerExit()
{
isInRotateZone = false;
referencetotext.text ="";
}
// Update is called once per frame
void Update () {
}
}
**Any help is appreciated**
↧
↧
GameObject.findGameObjectsWithTag returning empty?
I have one game object in my scene with the tag "Enemy", yet no matter what I try, GameObject.FindGameObjectsWithTag("Enemy") returns an empty array...
The variable I tried setting it to is indeed an array of GameObjects, and I even tried
Debug.Log(GameObject.FindGameObjectsWithTag("Enemy"));
while standing right next to the enemy, and it printed out "UnityEngine.GameObject[]"
Why won't it find my game object with the tag Enemy?
And P.S. please don't say to use FindGameObjectWithTag (SINGLE). There is only one now because it's a work in progress. The script is supposed to find many enemies at once
↧
FindGameObjectsWithTag finds destroyed gameobjects
Hi, Im creating an algorithm for automathic level generation. In order to evaluate my algorithm I want to run it some amount of times and meassure permormance values. I also need to perform a test each time to see if the level is correct. I do this by comparing how many rooms there are in the level with how many rooms the resposible script reported it would create (this is not very important for my problem, just some background).
The problem is that when I run the algoithm more than one time the GameObject.FindGameObjectsWithTag() returns all the rooms that was ever created. Even the ones that has been destroyed and are no longer in the scene.
Here are the most important parts of my code:
void Start ()
{
while (nrOfRepeats < repeats)
{
clearLevel();
nrOfRepeats++;
createLevel();
}
checkConnectivity();
}
void clearLevel ()
{
GameObject[] rooms = GameObject.FindGameObjectsWithTag("Room");
foreach (GameObject g in rooms)
Destroy(g);
}
void checkConnectivity ()
{
GameObject[] roomsInScene = GameObject.FindGameObjectsWithTag("Room");
Debug.Log(roomsInScene.Count());
}
Say I would run the while lopp three times and the algorithm would create 10 rooms, 15 rooms and finally 10 rooms. I would only see 10 rooms in the scene, but the output in the console would still be 35. Anyone has any ideas what the problem here is?
↧
Using a Parameterized arraylist (C#)???
I am trying to write a function to get all enemies with tag "Enemy" within range lockOnDistance, and return the list of them. I don't know how many enemies there will be in range, but I want to check the number of them so I can check the boolean version of this (i.e. "Are there enemies in range?" (is the size == 0)), so I have to use an arraylist instead of an array unless I want to go through every enemy and get the number in range (i,e, the size of the array), then go BACK THROUGH THEM ALL AGAIN and add them to the array, and surely there's a better way than that
Issues:
1) Why won't it let me say ArrayList?
2) It doesn't recognize ArrayList.add(E)????
↧
Can a tagged object exclude itself from FindGameObjectWithTag?
[This has already been asked once before][1], but as changing tags isn't an option for me, I'm wondering if any less hacky methods have been figured out since then or, failing that, if anybody could clarify how exactly one can use arrays to do what I'm trying to do; which isn't explained very clearly in the other question.
[1]: http://answers.unity3d.com/questions/233257/exclude-self-in-findgameobjectswithtag-.html
↧
↧
Trouble with List and FindObjectsWithTag
I'm having a problem trying to fill a list with GameObjects while using FindGameObjectsWithTag. I put this in a coroutine because the script exists before the level finishes loading, but even when the level is fully loaded, the script cycles indefinitely (until you stop running the game, or if you try to look at the script on the gameObject in the scene, at which point it will throw a null reference error). The spawn points definitely exist in the scene and are definitely tagged correctly, so I'm guessing its a dumb syntax mistake on my part, but I'm just not finding it.
Any ideas are appreciated.
IEnumerator CollectSpawnPoints () //coroutine because this script will exist before the spawnpoints are loaded,
{
while (spawnPointList == null)
{
Debug.Log ("attempting to find spawn points");
try
{
spawnPointList.AddRange (GameObject.FindGameObjectsWithTag("Respawn"));//.OrderBy(go => go.name).ToList());
//spawnPointArray = GameObject.FindGameObjectsWithTag("Respawn").OrderBy(go => go.name).ToArray();
}
catch
{
Debug.Log ("CollectSpawnPoints failed to find spawnpoints, trying again");
}
yield return null;
}
currentSpawnPoint = 0;
ResetToSpawn ();
Debug.Log ("the CollectSpawnPoints() coroutine has finished");
}
↧
Problem in finding objects with a particular tag
Okay, so I am working on a project for past few days now which is kind of a classic platformer with a player and some enemies. I was finding enemies in my scene using
FindGameObjectsByTag(EnemyTag);
Up until now everything was fine and dandy, but suddenly for some reason when I ran my game today it started returning me clones of my enemy game objects, even though I don't have them. I have just 2 enemies but its returning a length of 5. I tried using
Resources.FindGameObjectsOfType(...;
but to no avail.
I tried searching on the net but found just a temporary solution: change the tag.
Can someone tell me whats causing the problem and help me solve it?
↧
GetComponent NullReferenceException
Hello.
I have GameObject which got Sprite renderer and function that assigns sprite that loaded from resoures:
using UnityEngine;
using System.Collections;
public class LetterButtonScript : MonoBehaviour {
private int letterInt;
private Sprite mySprite;
private SpriteRenderer renderer;
private bool dead;
// Use this for initialization
void Start () {
renderer = GetComponent();
letterInt = -1;
dead = false;
}
// Update is called once per frame
void Update () {
}
///
/// Sets the letter.
///
/// Letter number.
public void setLetter(int letterNumber) {
letterInt = letterNumber;
mySprite = Resources.Load("letters/" + letterInt, typeof(Sprite)) as Sprite;
renderer.sprite = mySprite;
}
public int getLetterNumber() {
return letterInt;
}
}
I have onther script with function that Instansiates it:
buttonsPositions.z = 0f;
buttonsPositions.y = -2.7f;
buttonsPositions.x = -4f;
for (int i = 0; i < mysteryCharNumbers.Length; i++) {
letterButtons[i] = Instantiate(letterButtonPrototype, buttonsPositions, this.transform.rotation) as GameObject;
buttonsPositions.x += 0.65f;
}
After that I try to set sprite to LetterButtons
for (int i = 0; i < letterButtons.Length; i++) {
LetterButtonScript script = letterButtons[i].GetComponent();
script.setLetter(mysteryCharNumbers[i]);
}
However, it shows me NullReferenceException and shows me setLetter function
What I did wrong?
↧
how do i "findgameobjectswithtags"?
how do i find game objects that can be either in tag A or tag B?
lets say i got 3 factions in a game and some NPC from faction A needs to attack npcs from faction B and C, it needs to find the closest enemy that is tagged either as faction B or faction C
i tried GameObject.FindGameObjectsWithTag(["A", "B"]) and it gave me an error
i changed "FindGameObjectsWithTag" to "FindGameObjectsWithTags" (added an "s" at the end) and the error went away, i start the game and it doesnt work and im getting another error
how do i do this?
↧
↧
Exclude my gameObject tag from FindGameObjectsWithTag
now what i want to do is to get an array of GameObject with the function call FindGameObjectsWithTag, my problem is that i have the same tag name that i'm looking for, how can i ignore my tag name and get only results from other game objects (like put a layer of ignoring myself when searching) ?
↧
Applying Force to Game Objects with Tag Errors.
Hi there,
I'm still quite new at coding and have been trying for hours now to figure out how to get this part of my code to work.
Basically I'm rolling a ball over a collider (containing this script), the collider then destroys a wall by adding a force to everything tagged with 'DestroyBrick'. I've tried several different ways of writing the code and looked on here for answers as well as tutorials and scripts but so far not managed to figure out what is wrong exactly.
It'd be great if someone could point me in the right direction with this, thanks in advance!
----------
public class Destroy_Bricks : MonoBehaviour
{
public float DestroyForce = 5000f;
public GameObject[] DBR;
public GameObject DBRobj
// Use this for initialization
void Start ()
{
DBR = GameObject.FindGameObjectsWithTag("DestroyBrick");
for (int i = 0; i < DBR.Length; i++);
}
void OnTriggerEnter (Collider other) // make sure object has IS TRIGGER ticked!!!
{
for (DBRobj in DBR)
{
DBRobj.rigidbody.AddForce(-transform.forward * DestroyForce, ForceMode.Acceleration);
}
}
}
↧
Trouble getting if statement to work
I'm trying to enable disable some gameobjects with if statements and FindGameobjectWithTag.
Needless to say I'm not doing it wright :(
Here is my code
///Swirl01
public void SetSwirl (string mSwirl01) {
//Default
if (mSwirl01 == "1")
a = true;
b = false;
c = false;
if (mSwirl01 == "2")
a = false;
b = true;
c = false;
if (mSwirl01 == "3")
a = false;
b = false;
c = true;
GameObject.FindGameObjectWithTag("swirl01").renderer.enabled = a;
GameObject.FindGameObjectWithTag("swirl02").renderer.enabled = b;
GameObject.FindGameObjectWithTag("swirl03").renderer.enabled = c;
}
I get the error "name a,b,c doesn't exist in the current context".
Can someone here please shed some light on this ??
↧
AI script troubles
I created an AI script, but it is having trouble. The enemy I'm putting the script on is supposed to be able to be spawned into the map multiple times, so i have to use a FindGameObjectsWithTag function with the tag of waypoint.
However it does not work and that's why I need help with it, Here is the script.
var waypoints : Transform[];
var Target : Transform;
var roam : enemyhealth;
var mybody : GameObject;
function Start() {
waypoints = GameObject.FindGameObjectsWithTag("waypoint");
roam = mybody.GetComponent(enemyhealth);
InvokeRepeating("check",0,10);
InvokeRepeating("MOVEIT",0,0.01);
}
function check() {
if(roam.isroaming==true){
var index : int = Random.Range(1,waypoints.length);
var thePrefab : Transform = waypoints[index];
Target = thePrefab;
}
}
function MOVEIT() {
if(roam.isroaming==true){
var rotation = Quaternion.LookRotation(Target.position - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime);
transform.Translate(Vector3.forward * Time.deltaTime);
}
}
I know that line 8, with
waypoints = GameObject.FindGameObjectsWithTag("waypoint");
Is not the right syntax, but I'm not sure how to implement this. Any help would be kind.
↧
↧
How to use FindGameObjectWithTag to get 0
I've been trying to use a simple script to count the number of GameObjects to print to a GUI. I can't figure out how to properly do it. My difficulty is that Length always returns 1. How should I change this code?
public static int count = 0;
private GameObject[] getCount;
void Update () {
getCount = GameObject.FindGameObjectsWithTag("BallsTag");
count = getCount.Length;
}
↧
c# Get target gameobject from a list
Hi all, first time here and just begin learning scripting. :)
I have a script which is instantiated (many times) who need a target (transform).
I tried the code below but makes all scripts use the same target (the first one found).
public GameObject target;
// Use this for initialization
void Start () {
target = GameObject.FindGameObjectsWithTag ("Pivot");
}
I also tried using a list but i don't know how to get another target to each script (it keep choosing the first target).
Another test script with this error (error CS1579: foreach statement cannot operate on variables of type `UnityEngine.GameObject' because it does not contain a definition for `GetEnumerator' or is not accessible) :
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class manyTargets : MonoBehaviour
{
public GameObject target;
public List pivotTarget;
void Start ()
{
if (target != null)
{
foreach(GameObject go in target)
{
pivotTarget.Add(go);
}
}
}
}
I have try from yesterday to make it work with no luck.
I hope i can get some help because i'm out of ideas.
If i'm not to clear, sorry (english is not my first language :) ).
Thanks a lot.
↧
Need help finding the closet player to an enemy
Hi, my game can have upto 4 players in it, and I am trying to work out how to determine which player is closest to an enemy, but I cannot seem to make the following script work.
I was trying to search for all tagged players, store them and then iterate through them one by one.
It seems that you cannot pass multiple tags into FindGameObjectsWithTag and that is where my problem is as my players are tagged as the following:
Player1
Player2
Player3
Player4
Here is the script I am trying to use (i have hard coded "Player1" into the FindGameObjectsWithTag as I only have 1 player at the mo, so I can test enemy AI.
// Find the closest enemy
void FindClosestEnemy()
{
// Find all game objects with tag Player
GameObject[] gos;
gos = GameObject.FindGameObjectsWithTag("Player1");
var distance = Mathf.Infinity;
var position = transform.position;
// Iterate through them and find the closest one
foreach (GameObject go in gos)
{
var diff = (go.transform.position - position);
var curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
closest = go;
distance = curDistance;
}
}
target = closest;
}
Please can someone help?
↧