Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 /
avatar image
0
Question by Dachckol · Aug 28, 2012 at 02:33 PM · fpsaienemylagprevent

Why is this script causing a lot of lag?

Hello, I have been trying to create a simple enemy AI for a first person shooter. For some reason my AI script causes a lot of lag. Here is the script:

 var players:GameObject[];
 var player:GameObject;
 var speed:float;
 var hitrange:float = 1.5;
 var enemyprefab:Transform;
 var healthkitprefab:Transform;
 var ammokitprefab:Transform;
 
 var plr:plrstats;
 var enemy:enemystats;
 var best:int = 0;
 var current:int;
 
 var x:int = 0;
 
 var startpos:Vector3 = Vector3.zero;
 
 var canhit:boolean = true;
 
 var isspawned:boolean;
 
 function Start()
 {
     isspawned = false;
     startpos = transform.position;
     enemy = gameObject.GetComponent(enemystats);
 }
 
 function Update () {
     if (!isspawned)
     {
         spawn();
         return;
     }
     x++;
     players = GameObject.FindGameObjectsWithTag("Player");
     for(var plr:GameObject in players)
     {
         current = Vector3.Distance(transform.position, plr.transform.position);
         if (current > best)
         {
             player = plr;
             best = current;
         }
     }
         
     if (player == null) return;
     if (Vector3.Distance(transform.position, player.transform.position) > hitrange && !canhit)
     {
         canhit = true;
     }
     
     if (Vector3.Distance(transform.position, player.transform.position) < hitrange)
     {
         if (!canhit) return;
         plr = player.GetComponent(typeof(plrstats));
         plr.Damage(20);
         canhit = false;
     }
     
     if (enemy.isdead)
     {
         plr = player.GetComponent(typeof(plrstats));
         plr.points += 10;
         var bonus:Transform;
         bonus = Instantiate(enemyprefab, startpos, Quaternion.identity);
         bonus.name = "enemy";
         var x = Random.Range(1,20);
         if(x == 1){bonus = Instantiate(healthkitprefab, transform.position, Quaternion.identity); bonus.name = "healthkit";}
         if(x == 2){bonus = Instantiate(ammokitprefab, transform.position, Quaternion.identity); bonus.name = "ammokit";}
         GameObject.Find("pointer").guiText.text = "+";
          GameObject.Destroy(gameObject);
     }
 }
 
 function FixedUpdate()
 {
     if (player == null) return;
     if (canhit)
     {
         transform.rotation = Quaternion.Slerp(transform.rotation,Quaternion.LookRotation(player.transform.position-transform.position), speed);
         rigidbody.AddForce((transform.position-player.transform.position).normalized*speed*Time.deltaTime);
     }
 }
 
 function spawn()
 {
     yield WaitForSeconds(3);
     isspawned = true;
 }

There is over 10 enemies on the map when the game is running, each enemy has one of these attached. The lag doesn't appear until the enemies are spawned. When I took the things from the fixed update and put them in update the lag was replaced by the enemies not moving as they should. Could the lag be caused by fixedupdate?

How could I prevent the lag?

Thank You.

Comment
Add comment · Show 2
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 Seth-Bergman · Aug 28, 2012 at 03:09 PM 0
Share

for starters, this is odd:

 if (!isspawned)
 {
    spawn();
    return;
 }


 function spawn()
 {
     yield WaitForSeconds(3);
     isspawned = true;
 }

the yield means you are calling the spawn() function every frame for three seconds, which means a lot of simultaneous WaitForSeconds are running (not sure if this would cause a lot of lag)... and since "isspawned" doesn't seem to be used in this sample, I wonder where else it is being used...

either way, that could probably be in the Start:

 function Start()
 {
     isspawned = false;
     startpos = transform.position;
     enemy = gameObject.GetComponent(enemystats);
     yield WaitForSeconds(3);
     isspawned = true;
 }
avatar image Dachckol · Aug 28, 2012 at 03:19 PM 0
Share

Thanks for the reply. I used the awake function and the lag is practically gone. The cause of the rest of the lag is probably the amount of enemies there is on the map.

If anyone sees anything else that is inefficient and will slow the application down please tell me.

2 Replies

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

Answer by Eric5h5 · Aug 28, 2012 at 03:21 PM

Some things: you shouldn't do any Find commands, such as FindGameObjectsWithTag, in Update. Do it once and cache the results. Also your logic causes a new instance of the spawn function to be launched every frame for 3 seconds. Avoid checking things every frame when they only happen once, such as "isdead"...instead of having this in Update, make it a function that's called once when necessary. Finally, does this really need to be in Update at all? Update is for things that happen every frame; it seems likely that it really only needs to be done a few times per second maybe, so use InvokeRepeating or coroutines instead of Update.

Comment
Add comment · Show 1 · 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 Dachckol · Aug 28, 2012 at 03:30 PM 0
Share

Thank you! the lag is now completely gone.

avatar image
0

Answer by Sundar · Aug 28, 2012 at 03:19 PM

your culprit is x++ why you need it any way, even if you need it you should have controlled its value somewhere.

Also, cut this "players = GameObject.FindGameObjectsWithTag("Player");" from update() and paste it in Start(), its not a good idea to find players continuously in update()'s as its not going to give you two different result than calling it once at start()

Comment
Add comment · Show 1 · 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 Dachckol · Aug 28, 2012 at 03:30 PM 0
Share

Thanks for the reply.

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

10 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

Related Questions

Complete AI Tutorial? 1 Answer

Instantiate Projectile towards player (regardless of transform.rotation) 2 Answers

FPS Problem Help! 0 Answers

Hurting enemy when attacking status is equal to true and player is colliding with enemy object. 1 Answer

Deal damage on collision 2 Answers


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