Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
  • Help Room /
avatar image
0
Question by Marca59 · Oct 08, 2015 at 02:01 PM · teleport

How to fix problem IndexOutOfRangeException

How to fix

IndexOutOfRangeException: Array index is out of range. NewTeleport.Teleport () (at Assets/Assets slender/Standard Assets/Scripts/NewTeleport.js:155) NewTeleport.searchDistanceToPlayer () (at Assets/Assets slender/Standard Assets/Scripts/NewTeleport.js:166) NewTeleport.Update () (at Assets/Assets slender/Standard Assets/Scripts/NewTeleport.js:71)

//- Roam whenever the player is not seen by SM, and the player is not facing SM //- Move towards the player whenever player is seen by SM (not necessarily the player seeing him back), and the player is not facing SM //- Teleport to a legal position within a maximum and minimum range when: ///--- A. SM moves outside of the maximum range //--- B. SM roams for a random amount of time without seeing the player //--- C. The player is facing him (but does not see him), a random amount of time has passed, and there is still a chance he will not teleport at all

     #pragma strict
     var moveSpeed:float = 0.0;   // how fast slendy moves
     var maxRange:float = 0.0;   // the maximum range SM can be from the player without teleporting.
      var timer:int = 0;  // a little timer for function timing.
     var wayPoints:GameObject[];  // an array that stores all the waypoints for pathfinding.
     var player: GameObject;   /// the player gameObject, used for targeting
      var targetWaypoint: GameObject; // very important: the current waypoint marked for pathfinding.
     private var lastTarget:GameObject; // ignore this unless you really want to know what it does.
     var isMoving:boolean = false;    //checks if SM is moving. useful for determining whether to stay or roam.
      
     var pointer: GameObject;  // the pointer object used for spotting the player. Make sure it is not too high or too low.
     var range:int = 0;  // the range at which Slenderman can spot a player
     var canSee:boolean = false;  // if Slenderman can see the player (not vice versa or anything)
     var scanInterval:int = 0;   // how often to scan for player distance
      
     function Start () {
      
     wayPoints = GameObject.FindGameObjectsWithTag("waypoint");    // find all the GO's and store them off the start.
     player = GameObject.FindWithTag("Player");
      
     FindRoamPath();   // get us off pathfinding something
     }
      
     function Update () {
      
      
     ////the eye of the Slenderman//////////////////////////////
     ///////////////////you can use your own SM vision code here.
     ///////////////////just make sure canSee is true for proper movement.
     pointer.transform.LookAt(player.transform);
     var hit: RaycastHit;
     if (Physics.Raycast(pointer.transform.position,pointer.transform.forward,hit,range))
         {
             if (hit.collider.gameObject.tag == "Player")
                 {
         Debug.DrawRay(pointer.transform.position,pointer.transform.forward,Color.red);
             print(" can see!");
             canSee = true;
                 }
             else
                 {
                 canSee = false;
                 }
      
     }
     else if (!Physics.Raycast(pointer.transform.position,pointer.transform.forward,hit,range))
         {
         canSee = false;
         }
     ///////////////////////////////////////////////////////////////////////////////////////////////
      
     /////////////////a private timer. can be replaced with Time function for more accurate results.
     ////////////////////after a certain amount of time, search distance to player.
     ////////////////////the only reason this is set up as a function is because of performance reasons / teleport function
     timer++;
     if (timer > scanInterval)
         {
             searchDistanceToPlayer();
            
             timer = 0;
         }
        
        
         //search for new waypoint once I'm close to one.
     if (Vector3.Distance(transform.position,targetWaypoint.transform.position) < 1)  // this number can be changed on whatevs (depending on scale);
             {
                 if (!canSee)  //if I can't see the player. Just to make sure I'm actually roaming.
                     {
                 FindRoamPath();
                    }
             }
        
                
     if (isMoving)    //this does the actual movement.  movement is always the same, the target is what's different.
         {
     transform.position = Vector3.MoveTowards(transform.position,targetWaypoint.transform.position,moveSpeed * Time.deltaTime);
         }
        
        
     // If I can see the player, execute the function that finds a path to the the player
     // this is called everyframe because of SM visibility. a quick conditional will allow me to see if I can see the player (no pun intended)
     // if I can see him, then execute FindFollowPath(), which finds the nearest waypoint to the player (as if he is following him).
     if (canSee)
         {
             var nearpoint = FindFollowPath();
             if (lastTarget != nearpoint)            //if it's not the same, then keep on moving
                 {
             targetWaypoint = nearpoint.gameObject;
             lastTarget = nearpoint.gameObject; // prevents re-moving to same position - jittery
                 }
                 else
                 {
                 isMoving = false;     //you're close enough, stop moving. This works by checking if the same waypoint has been selected twice.
                 }
         }
      
     }
      
     function FindRoamPath()   //this doesn't do pathfinding. This just tells us the path to find. In this case, a random one.
         {
             isMoving = true;   // gotta get up off our feet
             var rand:int = Mathf.Floor(Random.Range(0,wayPoints.length));   // a random waypoint has been selected! 
             if (lastTarget != wayPoints[rand])  // similar to above. don't randomly pick the same spot.
                     {
                         targetWaypoint = wayPoints[rand]; // our target waypoint is now a random one from the list.
                         lastTarget = wayPoints[rand];
                     }
                     else
                     {
                     isMoving = false;
                     }
         }
      
     function FindFollowPath() : Transform   //if I see the player, find a path to his position.
         {
         // loop through each tagged object, remembering nearest one found. Original "find nearest" code by Ben Pitt.
         //http://answers.unity3d.com/questions/16676/how-can-i-make-my-gameobject-find-the-nearest-obje.html
         // basically what it does is go through the list of waypoints and finds the nearest one to the -player- through distance.
          var nearestDistanceSqr = Mathf.Infinity;
         var nearestObj : Transform = null;
        
         for (var obj : GameObject in wayPoints) {
      
             var objectPos = obj.transform.position;
             var distanceSqr = (objectPos - player.transform.position).sqrMagnitude;
      
             if (distanceSqr < nearestDistanceSqr) {
                 nearestObj = obj.transform;
                 nearestDistanceSqr = distanceSqr;
             }
         }
      
         return nearestObj;
     }
        
        
        
        
     function Teleport()    // take me to a random waypoint!   this function does not yet utilize legal (nearby) waypoints
         {
             var rand:int = Mathf.Floor(Random.Range(0,wayPoints.length));
             targetWaypoint = wayPoints[rand];   
             transform.position = wayPoints[rand].transform.position;
         }
        
        
     function searchDistanceToPlayer()   // find distance to player. Might as well check if I'm above range to teleport, too.
     {
     var curDistance:float;
     curDistance = Vector3.Distance(transform.position,player.transform.position);
     if (curDistance > maxRange)
             {
                 Teleport();
             }
      
     }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by Statement · Oct 10, 2015 at 01:31 PM

It looks like your problem is that the array wayPoints is empty.

Don't access wayPoints[rand] if wayPoints.length == 0.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Marca59 · Oct 10, 2015 at 01:51 PM 0
Share

I have in my game 5 paper. I am put in this move speed 3,I don't know what number I need put in max range and what gameobject I need put in target waypoint.sry for my bad english

avatar image Statement · Oct 10, 2015 at 02:06 PM 0
Share

Looking at the code, you need to make sure you have game objects in the scene with a tag called "waypoint" for it to work.

 // Code is looking for game objects tagged "waypoint"
 wayPoints = GameObject.FindGameObjectsWithTag("waypoint"); 

Documentation links:

  • FindGameObjectsWithTag

  • Tags

  • Tags and Layers manager

As for the values for the variables, I don't know what sensible values would be for your project. If unsure, don't be afraid to experiment with different values or making some effort to understand how they are used in code.

avatar image
-1

Answer by Landern · Oct 08, 2015 at 02:57 PM

Simple answer, don't try and access an item by index that is out of bounds of the capacity of the array.

You're getting a random value that may include more then the base zero index. Apply the index of an array that is base 0, meaning 0 is the first element you're going to be off by one. The random number you want is from 0(the first element) to the length of the array minus 1.

line 142 & 102:

 var rand:int = Mathf.Floor(Random.Range(0,wayPoints.length));

should look like

 var rand:int = Mathf.Floor(Random.Range(0,wayPoints.length - 1)); // Remember the index starts at 0, if you have 5 items and you don't take one away from the length, you will apply index 5 but since the array is 0 based(the first item in the array) you will be out of bounds since index 4 is the last item
Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Marca59 · Oct 10, 2015 at 12:33 PM 0
Share

IndexOutOfRangeException again on this line

targetWaypoint = wayPoints[rand];

and

if (lastTarget != wayPoints[rand])

$$anonymous$$aybe might be a problem because I do not know which currencies should be put in herealt text

avatar image Statement · Oct 10, 2015 at 01:29 PM 0
Share

@Landern: Random.Range already is exclusive of the maximum range for the integer overload, which is used here (float overload is inclusive, but that's not what OP is using). One should not subtract 1 in this example, or you would not get the full range of the arrays contents.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

33 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Rotating object to another objects rotation [C#] 1 Answer

Struggling with creating a Slender-like AI (Creating this for educational purposes) 0 Answers

How to teleport player in unity using X, Y, Z axis,How to teleport a player using X,Y,Z. 0 Answers

How to make a Teleporter Pad send Player to other random Teleporter Pad? 1 Answer

How can I make my player teleport to somewhere else on collision with object? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges