Questions in topic: "index"http://answers.unity.com/questions/topics/single/2744.html
The latest questions for the topic "index"Checking Material and Destroying Another Object C#http://answers.unity.com/questions/1599213/checking-material-and-destroying-another-object-c.html
Hi everyone, I'm making a game where I need two objects to collide and if the material and tag match the object is destroyed. (Side note I'm using an index to change materials).
For example if the objects material was 1 in the index (red) it would destroy objects with the tag red_block and the same would happen for the other three colours I am currently using.
I'm really unsure how I would go about coding this and the internet was no help so any advise would be really appreciated, thanks in advance.materialdestroy objectcheckindexThu, 07 Feb 2019 10:51:21 GMThellraiser9954how to find, not a specific child (GetChild(0)), but a range of child objects (GetChild(0 to 4))http://answers.unity.com/questions/1554802/how-to-find-not-a-specific-child-getchild0-but-a-r.html
there are 9 child gameobjects to a parent.
only one child is active at a time, rest are disabled.
I want to do something like
if current active childindex is less than 4 then setactive(false) all the children and setactive(true) childindex(0)
if current active childindex is between 4 - 9 then setactive(false) all the children and setactive(true) childindex(4)
currently I have if statement for all 9 childrens like so
if (transform.GetChild(1).gameObject.activeInHierarchy == true)
{
transform.GetChild(1).gameObject.SetActive(false);
transform.GetChild(0).gameObject.SetActive(true);
}
if (transform.GetChild(2).gameObject.activeInHierarchy == true)
{
transform.GetChild(2).gameObject.SetActive(false);
transform.GetChild(0).gameObject.SetActive(true);
}
and so on. but I know there must be a better way to deal with this. so please help. thanks in advance.transformchildrenindexWed, 19 Sep 2018 17:44:29 GMTacclogin71Dialogue problems?http://answers.unity.com/questions/1536576/dialogue-problems.html
The problem is that the text is not allowing me to exit after it has exceeded the index for some reason, and is adding the text at its original index. I'm very confused and have done all I can to try and fix it. Any help is very appreciated.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class DialogueManager : MonoBehaviour {
public Text textdisplay;
public Text nametext;
public string[] sentences;
public string[] names;
private int index;
private int end = 2;
public float typingspeed;
public GameObject uimanager;
public static bool displayText = false;
private bool isActive = false;
private string trig;
public GameObject continueButton;
public GameObject script;
void Start () {
}
private void Update()
{
trig = Clicker.trigname;
NameTxt();
Conversations();
if (displayText == true)
{
uimanager.SetActive(true);
}
else
{
uimanager.SetActive(false);
}
if (textdisplay.text == sentences[index])
{
continueButton.SetActive(true);
}
}
IEnumerator Type()
{
foreach (char letter in sentences[index].ToCharArray())
{
if(index <= end)
{
textdisplay.text += letter;
yield return new WaitForSeconds(typingspeed);
}
else
{
isActive = false;
displayText = false;
}
}
}
public void NextSentence()
{
continueButton.SetActive(false);
if (index < sentences.Length - 1 && index < end) {
index++;
textdisplay.text = "";
StartCoroutine(Type());
}
else
{
isActive = false;
displayText = false;
}
}
void NameTxt()
{
nametext.text = names[index];
}
//Problem: GOES BACK TO THE FIRST SENTENCE? THEN STOPS ALLOWING YOU TO EXIT.
void Conversations()
{
Conv1();
Conv2();
}
void Conv1()
{
if(trig == "conv1" && isActive == false)
{
index = 0;
end = 2;
isActive = true;
displayText = true;
StartCoroutine(Type());
}
}
void Conv2()
{
if (trig == "conv2" && isActive == false)
{
index = 3;
end = 5;
isActive = true;
displayText = true;
StartCoroutine(Type());
}
}
}c#loopindexdialogueTue, 31 Jul 2018 15:33:07 GMT3kWikiGamesHow to play animation from an array of gameObjects?http://answers.unity.com/questions/1527347/how-to-play-animation-from-an-array-of-gameobjects.html
Hello all,
I have a list (or an array) of gameobjects with the Animator component.
My goal is to setTrigger on each gameObject, such that the trigger happens each 10 seconds.
this is my script so far:
//public List<Animator> enemies = new List<Animator>(); //or a list
public Animator[] anim;
private void Start()
{
anim = GetComponentsInChildren<Animator>();
/*foreach (Transform t in transform) //in case of a list
{
enemies.Add(t.GetComponentInChildren<Animator>());
InvokeRepeating("SpawnEnemy", 10, 10);
}*/
}
private void SpawnEnemy()
{
for (int i = 0; i < anim.Length; i++)
{
anim[i].SetTrigger("FadeIn");
}
/*for (int i = 0; i < enemies.Count; i++) //in case of a list
{
enemies[i+1].SetTrigger("FadeIn");
}*/
currently this code returns null referencetriggeranimatorlistindexinvokerepeatingMon, 09 Jul 2018 20:09:31 GMTEco-EditorDialogue system with index, children, and parent.http://answers.unity.com/questions/1522977/dialogue-system-with-index-children-and-parent.html
What I want is that when I press Y, the current gameobject deactivates and the gameobject below it activates. Then when the last gameobject is reached and Y is pressed, the parent is deactivated. I'm trying to make a Text panel similar to that of Harvest Moon 64 or any other game actually. Where the NPC talks in like 3-4 boxes and then it disappears. It's more like a dialogue box.
Hey there everyone, I need help with something that I think is pretty easy to do, but it has me stumped. So what I'm trying to achieve is a dialogue sequence. The way I'm doing this is by having one parent gameobject that holds all the UI Text elements. I have DialogueSequence1 as the parent which holds all the UI Text elements as children and they're called TextPanel_1, TextPanel_2, etc. There's going to be a varying amount of these TexPanels and what I want is that when the player presses Y, the TextPanel that is currently active now, deactivates and the next TextPanel below it in the hierarchy activates and so on and so forth. I'm guessing that the easiest way to do this would be with some sort of index type of code, but I am not familiar with how to do that, and the internet isn't being too helpful. To give you an idea, think of pressing the A button to move onto what the NPC is going to say next in any game. That's what I'm trying to achieve. Here's a model:
NPC talks --> Player presses Y --> Next dialogue panels appears while the previous one deactivates --> so on and so forth until the last one --> on the last dialogue panel, the parent deactivates. This should work with just one text panel as well, if not I'll adjust.
I have some code that I wrote and this is it. Feel free to work off of that if you'd like.
public GameObject ObjectToDisable;
public GameObject ObjectToEnable;
public GameObject TextParentToDisable;
public int TextCounterMax; //This should be how many text panels you have
int TextCounter; // Don't forget that this only happens when the GameObject is actually active
private void Update()
{
if (Input.GetKeyDown(KeyCode.Y))
{
NextPanel();
}
if (TextCounter >= TextCounterMax)
{
TextParentToDisable.SetActive(false);
}
}
public void NextPanel()
{
ObjectToDisable.SetActive(false);
ObjectToEnable.SetActive(true);
TextCounter += 1;
Debug.Log(TextCounter);
}child objectparent-childindexdialoguedisable objectThu, 28 Jun 2018 03:31:51 GMTAlejandroBoss10Array index out of range after buildhttp://answers.unity.com/questions/1518416/array-index-out-of-range-after-build.html
Hello, In editor works good but after build there is error IndexOutOfRangeException: Index was outside the bounds of the array.
int rand = Random.Range(0, (cars.Length));
vehicle = Instantiate(cars[rand]);
I tried with cars.length-1 too but not working. There is only one element in cars array but will be more but at this time I want to make it works with one element in the array.
Why in editor it works but not after build?arrayindexout of rangeFri, 15 Jun 2018 09:29:27 GMTWenonUnityProgress is not definedhttp://answers.unity.com/questions/1505397/unityprogress-is-not-defined.html
Hey! Im trying to publish a game on Kongregate but i get this error 'UnityProgress' is not defined. Can someone help me, i really dont know what to do to fix this error. I can build the game as WebGL without any error, i can also play the game in the unity editor without any problem. But when i assign the index file to the kongregate upload site and try to play it the error comes up. I can also play the game as a build on my PC, without posting it on a website.unity 5webglindexSat, 12 May 2018 16:25:12 GMTNuclear_DeveloperSurvival Shooter LineRenderer.setPosition index out of boundshttp://answers.unity.com/questions/1501363/survival-shooter-linerenderersetposition-index-out.html
I am following the survival shooter tutorial, and am having issues. I would like to have all errors corrected, but it really isn't impacting gameplay that much. I added a second element under "Materials", but that hasn't changed anything. I know my approach to solving these issues probably needs to change, but this is all very new to me, so could I get some help with this issue? Here is the code
using UnityEngine;
public class PlayerShooting : MonoBehaviour
{
public int damagePerShot = 20;
public float timeBetweenBullets = 0.15f;
public float range = 100f;
float timer;
Ray shootRay = new Ray();
RaycastHit shootHit;
int shootableMask;
ParticleSystem gunParticles;
LineRenderer gunLine;
AudioSource gunAudio;
Light gunLight;
float effectsDisplayTime = 0.2f;
void Awake ()
{
shootableMask = LayerMask.GetMask ("Shootable");
gunParticles = GetComponentInChildren<ParticleSystem> ();
gunLine = GetComponentInChildren <LineRenderer> ();
gunAudio = GetComponentInChildren<AudioSource> ();
gunLight = GetComponentInChildren<Light> ();
}
void Update ()
{
timer += Time.deltaTime;
if(Input.GetButton ("Fire1") && timer >= timeBetweenBullets && Time.timeScale != 0)
{
Shoot ();
}
if(timer >= timeBetweenBullets * effectsDisplayTime)
{
DisableEffects ();
}
}
public void DisableEffects ()
{
gunLine.enabled = false;
gunLight.enabled = false;
}
void Shoot ()
{
timer = 0f;
gunAudio.Play ();
gunLight.enabled = true;
gunParticles.Stop ();
gunParticles.Play ();
gunLine.enabled = true;
gunLine.SetPosition (0, transform.position);
shootRay.origin = transform.position;
shootRay.direction = transform.forward;
if(Physics.Raycast (shootRay, out shootHit, range, shootableMask))
{
EnemyHealth enemyHealth = shootHit.collider.GetComponent <EnemyHealth> ();
if(enemyHealth != null)
{
enemyHealth.TakeDamage (damagePerShot, shootHit.point);
}
gunLine.SetPosition (1, shootHit.point);
}
else
{
gunLine.SetPosition (1, shootRay.origin + shootRay.direction * range);
}
}
}linerendererindexWed, 02 May 2018 21:36:08 GMTTulkas1Array index is out of rangehttp://answers.unity.com/questions/1497274/array-index-is-out-of-range-48.html
Apologies if there's already an answer to this, it's probably something obvious but I can't work it out. I'm getting an Array Index Out Of Range error on one of my lists.arrayindexSun, 22 Apr 2018 17:37:06 GMTPeteFL,"For" loop looping only once through my arrayhttp://answers.unity.com/questions/1463996/for-loop-looping-only-once-through-my-array.html
Yeah, I know, that error has been reported so many times, and I could fix it by myself so many times, that even I wonder if I am just blind or not.
I have an array[ , ] of Transforms, and two "For" loops, each one looping through one dimension of my array. My array of Tranforms collects all objects inside a grid, and depending on their position, places them at the index [gridWidth, gridHeight]. Nothing too complex so far.
I use this array to establish a correspondance with another script containing some characters linked to each prefab (e.g. 'B' for "BlueCube"). Each time it collects the corresponding character, and each time the code loops through my array, it gets the nex character and prints it into a .txt file.
My code is supposed to print a map. It starts by printing the first line (as expected), but it also print the rest of the lines below the first one. Logical, but it is not what I wanted ; the map is printed backwards.
So, I decided to read the last line of my array, THEN to decrement the index of my gridHeight, so that each line of my map is printed in the right order. And here comes the problem :
![alt text][1]
[1]: /storage/temp/110663-error.png
As you can see, my loops go through the first line correctly. But as soon as it starts looping through the second line, I get an error message. Here is my code (simplified, but the problem remains here) :
private Transform[,] allObjectsInForegroundLayer;
int Height = 5;
int Width = 5;
void Start(){
allObjectsInForegroundLayer = new Transform[gridSize.gridSizeWidth, gridSize.gridSizeHeight];
Place_Stuff_Here();
Start_Looping();
}
void Place_Stuff_Here(){
//Blablabla, I fill the array here. I know the problem doesn't come from here, since my map was actually filled with characters, even though it was printed backwards.
}
void Start_Looping(){
int mapWidth = 0;
for (int y = 0; y < Height; y++)
{
for (int x = 0; x < Width; x++)
{
print(x +", "+ (Height - 1 - y));
if (i == LayerMask.NameToLayer("Foreground") && allObjectsInForegroundLayer.Length > 0)
{
if (allObjectsInForegroundLayer[x + mapWidth, Height - 1 - y].transform.name != "NoneForeground")
caracterToprint = index.ReturnReceivedChar(allObjectsInForegroundLayer[x + mapWidth, Height - 1 - y].transform.name.Replace("(Clone)", null));
else
caracterToprint = index.ReturnReceivedChar(allObjectsInForegroundLayer[x + mapWidth, Height - 1 - y].transform.name);
}
file.Write(caracterToprint);
}
mapWidth += gridSize.gridSizeWidth;
}
For once, I absolutely don't know where that error comes from, I have already managed to print my map backwards. Basically, what I am trying to do is to get the last line of my array (the Height variable), substracting 1 to it so that it remains inferior to the length of my array, then each time it loops through, it substracts Y, so that if I have a Height of 5, the new index to check will be 4, then 3, then 2, etc...
As you could see on my picture, it goes through the 4th index very well, but as soon as it goes through the 3rd, it prints me that error. I am really sure my array is completely filled, since I've set many Debug.Log() to check its content.
Thanks for your answer.2darrayloopindexindexoutofrangeexceptionSun, 04 Feb 2018 11:17:49 GMTQuasar47Getting the Index number of lowest 7 ints in listhttp://answers.unity.com/questions/1460284/getting-the-index-number-of-lowest-7-ints-in-list.html
I have a case where a certain amount of shots are used in each round and put into an int. I have several rounds and store them in a list. I want to know the index values of the 7 lowest ints in the list so i can find the rounds where the least amount of shots were done. I have looked at doing something like `shots.FindIndex` but i cant make it work. Any help would be appreciated
Code:
public List<int> shots = new List<int>();
public int bestScore;
// Use this for initialization
void Start()
{
hits.Add(0);
hits.Add(1);
hits.Add(2);
hits.Add(3);
hits.Add(4);
hits.Add(5);
hits.Add(6);
hits.Add(7);
hits.Add(8);
}listintfindindexsearchFri, 26 Jan 2018 16:32:21 GMTThephil2988Insert object to the list in the script in real-time.http://answers.unity.com/questions/1460037/insert-object-to-the-list-in-the-script-in-real-ti.html
Hello there, my problem is as follow:
I have a normal list.
public List<Transform> targets;
I want two objects in this list, and then need to be able to update what object is in the index.
So if i have two objects in the index like:
Index 1: Object 1.
Index 2: Object 2.
Then i need to be able to update what object is in object 1 on the fly in the script, is this possible?
I tried using targets.insert(1, object3.transform), but it will keep adding objects to the list, not inserting it into just the index space.listaddindexinsertFri, 26 Jan 2018 03:01:22 GMTsunrisepulpHow to write correctly Array[!x]// to say if the index is not x then...http://answers.unity.com/questions/1457254/how-to-write-correctly-arrayx-to-say-if-the-index.html
I want to write something that can make all the objects of an array stay false if they dont have the right index that is defined by x so in programming language I thought it would look like this but its not :
Array[!x].SetActive(false);indexarray of gameobjectsSat, 20 Jan 2018 01:47:05 GMTIonictable46How can I find the index of an object in an array from that object's script?http://answers.unity.com/questions/1449640/how-can-i-find-the-index-of-an-object-in-an-array.html
Hey guys,
I have a situation in which I have a GameManager script that has an array of game objects called nodes, which are placed in various locations in the scene.
On each of these node objects, I have a script called Node. It has an OnMouseDown function in it. What I'm trying to do is when I click on one of these nodes, it sends information about the node's specific identity to the GameManager script.
The problem I'm having is that I can't figure out how to get the index number for a specific node from within that object's Node script. Is there a way to do this?
This is the code that I have:
GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
public GameObject [] nodes;
public int indexNumber;
void Update ()
{
Debug.Log(indexNumber);
}
}
Node.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Node : MonoBehaviour {
public GameManager _gameManager;
void Start ()
{
_gameManager = GetComponent<GameManager>();
}
void OnMouseDown()
{
_gameManager.indexNumber = 0; // "0" is a substitute for what I would put to find the actual index number for this object in the array
}
}arraysindexWed, 03 Jan 2018 09:32:11 GMTMerlinsMasterCan someone tell me what is wrong with this?http://answers.unity.com/questions/1449565/can-someone-tell-me-what-is-wrong-with-this.html
characterList [index].tag =('Player');
Im trying to tag the gameobjects in the array as player tag.c#arraysplayerprefsindexload sceneWed, 03 Jan 2018 05:47:38 GMTSeanWinkCreating Mesh - Vertices out of boundrieshttp://answers.unity.com/questions/1406628/creating-mesh-vertices-out-of-boundries.html
Hello everyone o/
I'm to make a program that initializes an Icosphere (A sphere that consists out of triangles that have the same size and distance) from the script, where I can set the number of iterations for the sphere. The first creation of the sphere with 20 triangles works fine. But if I try to add more triangles recursively, I get this error:
>Failed setting triangles. Some indices are referencing out of bounds vertices. IndexCount: 240, VertexCount: 42
I'm confused about that: My vertices and my indices range from 0-41 and from 0-239. But there should be no further Vertex at the next position.
Has anybody an idea, what I could have done wrong? What do I not see? :/
Here is my code:
public class GenerateIcosphere : MonoBehaviour {
public List<Vector3> newVertices;
public List<Vector2> newUV;
public List<int> newTriangles;
public Material wireframe;
public int recrusionLevel = 0;
private int triLevel = 0;
private Dictionary<Int64, int> middlePointIndexCache;
private Mesh iSphere;
private void createIcosphere()
{
middlePointIndexCache = new Dictionary<long, int>();
float t = (float)(1.0 + Mathf.Sqrt(5.0f) / 2.0f);
newVertices = new List<Vector3> { new Vector3(-1, t, 0), new Vector3(1, t, 0),
new Vector3(-1, -t, 0),new Vector3(1, -t, 0),
new Vector3(0, -1, t), new Vector3(0, 1, t),
new Vector3(0,-1, -t), new Vector3(0, 1, -t),
new Vector3(t, 0, -1), new Vector3(t, 0, 1),
new Vector3(-t,0, -1), new Vector3(-t, 0, 1)};
newTriangles = new List<int> {0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1};
}
bool checkForDifference(int n)
{
if(n > triLevel || n < triLevel)
{
triLevel = n;
return true;
}
return false;
}
void iterateIcosphere()
{
for (int i = 0; i < recrusionLevel; i++)
{
List<int> addTriangles = new List<int> { };
for (int j = 0; j < newTriangles.Count; j = j+3)
{
int a = getMiddlePoint(newTriangles[j], newTriangles[j+1]);
int b = getMiddlePoint(newTriangles[j+1], newTriangles[j+2]);
int c = getMiddlePoint(newTriangles[j+2], newTriangles[j]);
addTriangles.Add(newTriangles[j]);
addTriangles.Add(a);
addTriangles.Add(c);
addTriangles.Add(newTriangles[j+1]);
addTriangles.Add(b);
addTriangles.Add(a);
addTriangles.Add(newTriangles[j+2]);
addTriangles.Add(c);
addTriangles.Add(b);
addTriangles.Add(a);
addTriangles.Add(b);
addTriangles.Add(c);
}
newTriangles = addTriangles;
}
}
private int addVertex(Vector3 p)
{
float length = Mathf.Sqrt(p.x * p.x + p.y * p.y + p.z * p.z);
newVertices.Add(new Vector3(p.x / length, p.y / length, p.z / length));
return newVertices.Count;
}
private int getMiddlePoint(int p1, int p2)
{
//check if the point already exists
bool firstIsSmaller = p1 < p2;
Int64 smallerIndex = firstIsSmaller ? p1 : p2;
Int64 greaterIndex = firstIsSmaller ? p2 : p1;
Int64 key = (smallerIndex << 32) + greaterIndex;
int ret;
if (middlePointIndexCache.TryGetValue(key, out ret))
{
return ret;
}
//if not calculate new point
Vector3 point1 = newVertices[p1];
Vector3 point2 = newVertices[p2];
Vector3 middle = new Vector3(((point1.x + point2.x) /2.0f),
((point1.y + point2.y) / 2.0f),
((point1.z + point2.z) / 2.0f));
int i = addVertex(middle);
middlePointIndexCache.Add(key, i);
return i;
}
void Start () {
createIcosphere();
iSphere = new Mesh();
gameObject.AddComponent<MeshFilter>().mesh = iSphere;
iSphere.vertices = newVertices.ToArray();
iSphere.uv = newUV.ToArray();
iSphere.triangles = newTriangles.ToArray();
iSphere.RecalculateNormals();
gameObject.AddComponent<MeshRenderer>();
gameObject.GetComponent<MeshRenderer>().material = wireframe;
}
// Update is called once per frame
void Update () {
if (checkForDifference(recrusionLevel))
{
iterateIcosphere();
iterateUVs();
iSphere = new Mesh();
gameObject.GetComponent<MeshFilter>().mesh = iSphere;
iSphere.Clear();
iSphere.vertices = newVertices.ToArray();
iSphere.uv = newUV.ToArray();
iSphere.triangles = newTriangles.ToArray();
iSphere.RecalculateNormals();
}
}meshverticesindexWed, 13 Sep 2017 22:51:43 GMTJenny_WasjaArgumentException: Index out of bounds. Help?http://answers.unity.com/questions/1404936/argumentexception-index-out-of-bounds-help.html
Current script, I am trying to add a touch feature to add money.
public class AddReducePlayerMoney : MonoBehaviour
{
public int money;
public GameObject cam;
void Update()
{
Touch myTouch = Input.GetTouch(1);
Touch[] myTouches = Input.touches;
for(int i = 1; i < Input.touchCount; i++)
{
if (Input.GetButtonDown("Fire1"))
{
cam.GetComponent<PlayerMoney>().addMoney(5);
}
if (Input.GetButtonDown("Fire2"))
{
cam.GetComponent<PlayerMoney>().subtractMoney(5);
}
}
}
}touchtouchscreenindexoutofboundsSun, 10 Sep 2017 02:20:13 GMTcrypticscottIndexOutOfRangeException: IndexOutOfRangeException: Array index is out of range. FollowTarget.Update () (at Assets/Scripts/FollowTarget.cs:29)http://answers.unity.com/questions/1404592/indexoutofrangeexception-indexoutofrangeexception.html
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;
public class FollowTarget: MonoBehaviour
{
public Transform[] traget;//tragets
public float tragetDistanceOffset = 0.1f;//target offset
public bool reachedTarget;//reached target flag
public bool isRunning = true;//is running flag
public bool stopFollowAfterReachTarget;//stop follow flag
public float speed = 10;//follow speed
public bool followX, followY, followZ;//follow x,y,z flags
public int tragetIndex = 0;//target index
private float xpos, ypos, zpos;//x,y,z positions
private float smoothDampVelocity = 0;//smooth damp velocity
public FollowMethod followMethod = FollowMethod.LERP;//follow method
void Start ()
{
if (traget == null) {
traget = new Transform[1];
}
}
// Update is called once per frame
void Update ()
{
if (!isRunning || traget [tragetIndex] == null) {
return;
}
if (reachedTarget) {
if (stopFollowAfterReachTarget) {
return;
}
}
if (followX) {
xpos = GetValue (transform.position.x, traget [tragetIndex].position.x);//set x position
} else {
xpos = transform.position.x;//set x position
}
if (followY) {
ypos = GetValue (transform.position.y, traget [tragetIndex].position.y);//set y position
} else {
ypos = transform.position.y;//set y position
}
if (followZ) {
zpos = GetValue (transform.position.z, traget [tragetIndex].position.z);//set z position
} else {
zpos = transform.position.z;//set z position
}
transform.position = new Vector3 (xpos, ypos, zpos);//set the position
if (Mathf.Abs (Vector3.Distance (traget [tragetIndex].position, transform.position)) <= tragetDistanceOffset) {//when the gameobject reached the target
this.reachedTarget = true;
}
}
public enum FollowMethod
{
LERP,
SMOOTH_DAMP,
SMOOTH_STEP,
MOVE_TOWARD
} ;
//Get the follow postion value
private float GetValue (float currentValue, float targetValue)
{
float returnValue = 0;
if (followMethod == FollowMethod.LERP) {
returnValue = Mathf.Lerp (currentValue, targetValue, speed * Time.deltaTime);
} else if (followMethod == FollowMethod.MOVE_TOWARD) {
returnValue = Mathf.MoveTowards (currentValue, targetValue, speed * Time.smoothDeltaTime);
} else if (followMethod == FollowMethod.SMOOTH_DAMP) {
returnValue = Mathf.SmoothDamp (currentValue, targetValue, ref smoothDampVelocity, speed);
} else if (followMethod == FollowMethod.SMOOTH_STEP) {
returnValue = Mathf.SmoothStep (currentValue, targetValue, speed * Time.smoothDeltaTime);
}
return returnValue;
}
}androidarraydrag-and-dropindexSat, 09 Sep 2017 12:28:36 GMTwilhoran11Can I check if pair of indexes are in range of the matrix?http://answers.unity.com/questions/1403356/can-i-check-if-pair-of-indexes-are-in-range-of-the.html
Hi there, I'm making strategy game with tiles - every tile has unique index number that it gets recognized with and i have a matrix of those indexes that represends whole board. It looks like so (it's smaller sample to make is easier to understand).
int[,] fieldIndexMatrix = new int[3, 3];
/*
after initialization with indexes, example!
\ y
x \ 0 1 2
\___________________
| | | |
0 | 0 | 1 | 2 |
|_____|_____|_____|
| | | |
1 | 3 | 4 | 5 |
|_____|_____|_____|
| | | |
2 | 6 | 7 | 8 |
|_____|_____|_____|
*/
So in the middle is field with index 4 and you get it by fieldIndexMatrix[1, 1], bottom left is field with index 6 and you get it by fieldIndexMatrix[2, 0], you get the idea :)
And let's now say that i want some effect that will affect some targeted field and adjacent ones. Area of effect will be + looking so i need to find right, left, bottom, and upper field relative to targeted one.
I can find them by doing so:
List<int> adjacentIndexes = new List<int>();
int x;// x coordinate of the matrix
int y;// y coordinate of the matrix
int a;
int b;
a = x + 1;
b = y;
adjacentIndexes.Add(fieldIndexMatrix[a, b]);
a = x - 1;
b = y;
adjacentIndexes.Add(fieldIndexMatrix[a, b]);
a = x;
b = y + 1;
adjacentIndexes.Add(fieldIndexMatrix[a, b]);
a = x;
b = y - 1;
adjacentIndexes.Add(fieldIndexMatrix[a, b]);
return adjacentIndexes.ToArray();
While it will work for the fields in the middle It won't for the fields on the edge. If my targeted field has coordinate x = 0 and I'll try to find x - 1 I'll get and error "IndexOutOfRangeException: Array index is out of range." and my script will just stop there. but i don't want it to stop!!!
I want it to keep going and finding indexes. If it can't find an index because the coordinates for the matrix are out of range I just want to ignore this part and go to the next step. Is there some function or trick that can tell me If array index is in range of the matrix or not?
I tried doing
if(fieldIndexMatrix[a, b] != null)
adjacentIndexes.Add(fieldIndexMatrix[a, b]);
but it does not seem to work. Any Idea?matrixindexout of rangeWed, 06 Sep 2017 11:39:39 GMTSpeedo0Insert a string to a list inside a listhttp://answers.unity.com/questions/1400173/insert-a-string-to-a-list-inside-a-list.html
**I want to set the string of an index from a list that's inside a list**
So I got a variable like this:
var everyRow = new List.< List.<String> >();
My attempt at accessesing the inner List is by:
everyRow.Insert(e, List.<String>());
everyRow[e].Insert(ee, currentLog[ee]);
That line gives me this error though:
ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index
So I'm guessing there's a better way to solve this.
Help?javascriptlistindexargumentoutofrangeexceptionTue, 29 Aug 2017 09:07:40 GMTvaltteri_mHow can I get a data from function to other function?http://answers.unity.com/questions/1397164/how-can-i-get-a-data-from-function-to-other-functi.html
I have this function
public void InitButtons () {
Transform currentChild;
for (int i = 0; i < buttonsContainer.childCount; i++) {
currentChild = buttonsContainer.GetChild (i);
buttonlist [i / column, i % column] = currentChild.GetChild (0).GetComponent<Text> ();
currentChild.GetComponent<Buttons> ().buttonIndex = i;
And I want to get the data of "i" variable in other function.
How can I solve this problem ?buttonspublicindexpublic variableclick objectsTue, 22 Aug 2017 07:45:00 GMTPizzaPablo666Failed receiving RPC batch indexhttp://answers.unity.com/questions/1396219/failed-receiving-rpc-batch-index.html
So I'm working on my game 2 years now and this strange error has started happening recently only when some player connects to a host. When I'm alone on a server error won't appear... But this error only happen in editor console log. When I'm playing on development build with console there's no such error like that... I searched forums and answers and didn't found any solution Thanks for any help !!
![alt text][1]
[1]: /storage/temp/100239-snimka-obrazovky-1428.pngnetworkingmultiplayerrpcindexbatchSun, 20 Aug 2017 10:47:42 GMTPogyManTV[help] Array index is out of rangehttp://answers.unity.com/questions/1385471/array-index-is-out-of-range-43.html
So in another script i call the method loselife(); when an object is triggered and when the method is called it says ' Array index is out of range' i changed this.getcomponent().sprite=[lives-1] to this.getcomponent().sprite=[1] and it seemed to work, so why does it not work the first time is my question.
Here is the code :
using UnityEngine;
using System.Collections;
public class Lives : MonoBehaviour {
public Sprite[] liveSprites;
private int lives;
private int liveIndex;
private LevelManager LevelManager;
void start() {
LevelManager = GameObject.FindObjectOfType<LevelManager>();
lives = 3;
}
public void loseLife() {
lives--;
assignSprite();
}
void assignSprite() {
this.GetComponent<SpriteRenderer>().sprite=liveSprites[lives - 1];
}
}c#arrayvariablerangeindexFri, 11 Aug 2017 07:20:30 GMTfinlay_morrisonError when trying to run webGL application in firefox or chromehttp://answers.unity.com/questions/1389651/error-when-i-try-to-run-webgl-application-in-firef.html
Hello guys,
I get this error when I try to launch the index.html file through firefox. I do not understand to anything it says. "BB_WEB" is the name of my folder. Does anyone know where the problem is?
An error occurred running the Unity content on this page. See your browser's JavaScript console for more info. The error was: uncaught exception: abort(161) at jsStackTrace (BB_WEB.js:1:19540) stackTrace (BB_WEB.js:1:19711) abort (BB_WEB.js:3:31950) ljp (blob:28:1) _Jk (blob:4:1) IQg (blob:13:1) PWg (blob:13:1) T4k (blob:4:1) G9o (blob:28:1) invoke_iiii (BB_WEB.js:1:350286) mio (blob:19:1) slo (blob:19:1) F9 (blob:7:1) Zua (blob:14:1) pRb (blob:12:1) iRb (blob:12:1) wpb (blob:10:1) RQb (blob:12:1) Laa (blob:7:1) zya (blob:14:1) Jva (blob:14:1) Lva (blob:14:1) Dva (blob:14:1) fua (blob:14:1) eua (blob:14:1) cua (blob:14:1) $ta (blob:14:1) Jia (blob:14:1)
Here is a messagefrom the console:
Decompressed Release/BB_WEB.datagz in 781ms. You can remove this delay if you configure your web server to host files using gz compression. UnityLoader.js:1
Initialize engine version: 5.5.1f1 (88d00a7498cd)
Creating WebGL 2.0 context. UnityLoader.js:2
Renderer: Mozilla
Vendor: Mozilla
Version: OpenGL ES 3.0 (WebGL 2.0)
GLES: 3
EXT_color_buffer_float GL_EXT_color_buffer_float EXT_texture_filter_anisotropic GL_EXT_texture_filter_anisotropic EXT_disjoint_timer_query GL_EXT_disjoint_timer_query OES_texture_float_linear GL_OES_texture_float_linear WEBGL_compressed_texture_s3tc GL_WEBGL_compressed_texture_s3tc WEBGL_debug_renderer_info GL_WEBGL_debug_renderer_info WEBGL_lose_context GL_WEBGL_lose_context MOZ_WEBGL_lose_context GL_MOZ_WEBGL_lose_context MOZ_WEBGL_compressed_texture_s3tc GL_MOZ_WEBGL_compressed_texture_s3tc
OPENGL LOG: Creating OpenGL ES 3.0 graphics device ; Context level <OpenGL ES 3.0> ; Context handle 1
UnloadTime: 1.690000 ms
ArgumentNullException: Argument cannot be null.
Parameter name: url
(Filename: currently not available on il2cpp Line: -1)webglindexSat, 05 Aug 2017 10:23:02 GMTxxlukyList<> Size Changes Without Removing Elementshttp://answers.unity.com/questions/1375702/list-size-changes-without-removing-elements.html
Extremely weird issue. I declare a List of ints and add to it. Later on, after one of the values in the list becomes 0, that specific item is removed.
However, I've noticed that the value for the list size changes seemingly arbitrarily. See code:
public void InitializeGrid(List<float> ratios)
{
myRand = new SysRand();
// This method creates the grid after the user inputs the necessary initial and transition information
// make sure ratios is as big as our numStates
while (ratios.Count < numStates)
ratios.Add(0);
while (ratios.Count > numStates)
ratios.Remove(ratios.Last());
//Get a list of how many cells of each type we need
List<int> agentCount = new List<int>();
//int totalCells = gridWidth * gridHeight;
int totalAgents = 0;
for (int i = 0; i < numStates; ++i)
{
agentCount.Add((int)ratios[i]);
totalAgents += (int)ratios[i];
Debug.Log("Hi!");
Debug.Log(agents.Count);
}
// this is a list of which states still needed to be added
List<int> stateIndex = new List<int>();
for (int i = 0; i < numStates; ++i)
stateIndex.Add(i);
float[] agentAmountPerState = GetAgentAmountPerState(ratios);
for (int i = 0; i < gridWidth; ++i)
{
for (int j = 0; j < gridHeight; ++j)
{
// Get a random number for the states left to do and set it to the grid
// we can't just use the number directly because stateIndex
// could be 0,3,4 if we've finished setting all the 1s and 2s
//Debug.Log(i + ", " + j);
int index = GetIndexFromRange(agentAmountPerState);
int state = stateIndex[index];
grid[i, j] = new BlankGrid();
grid[i, j].AddAgent();
grid[i, j].agent.currentState = state;
grid[i, j].containsAgent = true;
//uygugykhkjhb;//THIS NEEDS double-checked. Should only fire (I think) if the grid location contains an agent.
// Subtract that state from its agentcount
// And if it goes to zero remove it from both our lists
Debug.Log(agentCount.Count);
for (int g = 0; g < agentCount.Count; g++)
{
Debug.Log(agentCount[g]);
Debug.Log(agentCount.Count);
}
agentCount[index]--;
if (agentCount[index] == 0)
{
Debug.Log(index);
Debug.Log(agents.Count);
agents.RemoveAt(index);
stateIndex.RemoveAt(index);
ratios.RemoveAt(index);
agentAmountPerState = GetAgentAmountPerState(ratios);
}
}
}
}
I'm not sure how to write the console output to a file, but when I run the program and choose 2 "numStates," I get (for **line 20** or so):
Hi!
0
Hi!
0
So it's telling me that the count is zero, even though it's CLEARLY counting off the appropriate number of times.
Next, for the for loop and the Debug.Log before it (**line 49**), I DO get the correct number--2 in my case.
Then, after the index falls to 0 and agentCount is checked (**line 59**), it is magically 0, before the removal of the list item is even attempted (and the attempted removal throws an argument out of range exception).
I don't have the slightest clue what I'm doing wrong . Can anyone help me?c#listindexcountdebug.logSat, 08 Jul 2017 07:40:59 GMTEternalAmbiguityIndexOutOfRangeException: Array index is out of range.http://answers.unity.com/questions/1354014/indexoutofrangeexception-array-index-is-out-of-ran-44.html
Ten times I run the program once will show me this error .........
IndexOutOfRangeException: Array index is out of range. dataLoader+c__Iterator0.MoveNext () (at Assets/1magazi/dataLoader.cs:193) UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)
in items[1] Can anyone help me with this ????
----------
WWW itemsData = new WWW("http://magazi1.000webhostapp.com/magazi_1/Datas.php");
yield return itemsData;
// var items = new GameObject[20];
string itemsDataString = itemsData.text;
string[] items;
items = itemsDataString.Split(';');
yield return itemsData;
if (GetDataValue(items[1].ToString(), "situation:").ToString() == "free")
{
Table_1_mavro.enabled = true;
Table_1_redd2.enabled = false;
}arrayindexSat, 20 May 2017 08:48:43 GMTmang-62[ANSWERED] IndexOf and LastIndexOf both returning -1 when an item is on the list.http://answers.unity.com/questions/1352688/indexof-and-lastindexof-both-returning-1-when-an-i.html
Ive been working on a simple inventory system in unity, and this problem has been driving me nuts for a couple days now
i have a very simple inventory system that stores the transforms of various inventory icons in a list, and i am trying to code a "drop" function that will remove specific items from the list, so that they no longer appear in the inventory.
I have tried using both "IndexOf" and "LastIndexOf" and both of them are returning -1 as if the item was not listed, but as far as i can tell, the item is definitely listed.
here is some sample code
//transform that was previously added to list
public Transform thistrans;
//attempting to find the index of said item
itemlist = invmanager.GetComponent<ItemLists>();
toRemove = itemlist.weaponimages.LastIndexOf(thistrans);
print (toRemove);
if anyone wants additional info please ask, thanks.listlistsindexindexofindexing-arrayFri, 12 May 2017 20:41:44 GMTVonricterIs it better to store index list or object itself ?http://answers.unity.com/questions/1344929/is-it-better-to-store-index-list-or-object-itself.html
First of all, sorry for the mistakes, english is not my native tongue.
I will try to explain clearly my question :
I have a class, named "character", which contain informations about my characters, like first name, surname, etc...
All existing characters are stored into a list, named "charactersList", and each time i create a new character, i add it to this list. Like this :
public class Character : MonoBehaviour {
public static List<Character> characterslist;
public Character()
{
characterslist.Add(this);
}
I want to create a variable 'father' who contain a reference to another character.
Knowing that I will never sort the 'characterList' list, is it better to store the index list in the variable 'father' or directly the character ?
Here is an example :
I have my character Luke that i just created, and i want to store his father Anakin who's stored at index 42 in the 'characterList'.
Should i do :
Luke.father = 42;
Or
Luke.father = characterList[42];
Hope i'm clear and thanks for your help.listvariablesindexMon, 24 Apr 2017 19:59:30 GMTJustineDFinding specific index of an arrayhttp://answers.unity.com/questions/1344835/finding-specific-index-of-an-array.html
I just cant seem to solve this little problem. I know that there is a lot of documentation on this subject, but none of those seems to help me.
Just to simplify the problem, lets say i have a few Buttons (unitys UI stuff) which all are part of an array. When i click one of the buttons, i want to know what that certain buttons index number is from the array.
From what i have found out, alot of people say that you could use System.Array.IndexOf. But i dont see how that could help me, or in other words, i dont get it to work.
Does anyone have any ideas?arraysindexMon, 24 Apr 2017 15:23:29 GMTprimusSpenatHow can i make a door-key script to a multiple keys and doors?http://answers.unity.com/questions/1334496/how-can-i-make-a-door-key-script-to-a-multiple-key.html
Hi, how can i make a door-key script to a multiple keys and doors? (like in index)
The script is JavaScript.
Her the original script:
//Text variables
public bool T_ActivatedOpen = true;
public bool T_ActivatedClose = false;
public bool activateTrigger = false;
public GameObject textO;
public GameObject textC;
//Animator variables
Animator Door_Animtion_Cell_001;
//animator;
bool doorOpen;
//Sound variables
public GameObject doorOpenSound;
public GameObject doorCloseSound;
void Start () { //what happens in the beginning of the game.
textC.SetActive (false);
textO.SetActive (false);
T_ActivatedOpen = true;
T_ActivatedClose = false;
Door_Animtion_Cell_001 = GetComponent<Animator> ();
doorOpen = false;
doorCloseSound.SetActive (false);
doorOpenSound.SetActive (false);
}
void Update () { //The main function wich controlls how the system will work.
if (T_ActivatedOpen == true)
T_ActivatedClose = false;
else if (T_ActivatedClose == true)
T_ActivatedOpen = false;
if (activateTrigger && Input.GetKeyDown (KeyCode.E)) //For some reaseon you can't have both E (open and close).
{
textO.SetActive (false);
textC.SetActive (false);
T_ActivatedOpen = false;
T_ActivatedClose = true;
textO.SetActive (false);
textC.SetActive (true);
doorOpen = true;
doorOpenSound.SetActive (true);
doorCloseSound.SetActive (false);
if (doorOpen)
{
doorOpen = true;
doorController ("Open");
}
}
else if(T_ActivatedClose && activateTrigger && Input.GetKey (KeyCode.F))
{
T_ActivatedOpen = true;
T_ActivatedClose = false;
textO.SetActive (true);
textC.SetActive (false);
doorCloseSound.SetActive (true);
doorOpenSound.SetActive (false);
if (doorOpen)
{
doorOpen = false;
doorController ("Close");
}
}
}
void OnTriggerEnter(Collider col) //If you enter the trigger this will happen.
{
if(col.gameObject.tag == "Player")
{
activateTrigger = true;
if((T_ActivatedOpen == true))
textO.SetActive (true);
if((T_ActivatedClose == true))
textC.SetActive (true);
}
}
void OnTriggerExit(Collider col) //If you exit the trigger this will happen.
{
if(col.gameObject.tag == "Player")
{
textO.SetActive (false);
textC.SetActive (false);
activateTrigger = false;
}
}
void doorController(string direction) //Animator function.
{
Door_Animtion_Cell_001.SetTrigger(direction);
}
Thanks in advance! :)doorkeyindexMon, 03 Apr 2017 06:46:26 GMTDOR2199