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 /
avatar image
0
Question by cublai · Mar 14, 2020 at 04:37 PM · colortimelerpontriggerstayzone

How to make OnTriggerStay ColorLerp start all over again OnTrigger?

Hi,

My code is not working properly. I want my Player to change color overtime when it is located in a Zone. It does work when I am in the first Zone, but when i go to another Zone, which has the same tag as the first one, It continues the Lerp where it ended in the first Zone.

So basically I am asking, if there is any way to reset to the StartColor everytime I am in a Zone? Or do you have any other sollutions?

Thanks a lot guys!

 using System.Collections;
  using System.Collections.Generic;
  using UnityEngine;
  
  public class ChangeColorOnTrigger : MonoBehaviour
  {
       public float speedIn = 1.0f;
       public float speedOut = 1.0f;
     public Color startColor;
     public Color endColor;
     float startTime;
 
 
  
      // Start is called before the first frame update
      void Start()
      {
          startTime = Time.time;
      }
  
   void OnTriggerStay(Collider col){
       if (col.gameObject.tag == "zone1"){
             float t = (Time.time - startTime) * speedIn;
             GetComponent<Renderer>().material.SetColor("_BaseColor",  Color.Lerp(startColor, endColor, t));
         }
   }
 
 void OnTriggerExit(Collider col){
       if (col.gameObject.tag == "zone1"){
             float t = (Time.time - startTime) * speedOut;
             GetComponent<Renderer>().material.SetColor("_BaseColor",  Color.Lerp(endColor, startColor, t));
         }
      }
   }
   


Comment
Add comment · Show 1
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 Frodo_21 · Mar 14, 2020 at 05:32 PM 0
Share

Have yout tried the "OnTriggerEnter" $$anonymous$$ethod ?

2 Replies

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

Answer by cublai · Mar 15, 2020 at 07:48 AM

It is working for me like this. Thanks a lot @JPhilipp!

  using System.Collections;
  using System.Collections.Generic;
  using UnityEngine;
  
  public class ChangeColorOnTrigger : MonoBehaviour
   {
       [SerializeField] Color endColor;
       Color startColor;
   
       const float speed = 1f;
       const string colliderTag = "zone1";
   
       Color? targetColor1 = null;
       Color? targetColor2 = null;
       Material material = null;
       float lerpAmount = 0f;
          
       void Awake()
       {
           material = GetComponent<Renderer>().material;
           startColor = material.color;
       }
   
       void Update()
       {
           FollowTargetColor();
       }
   
       void FollowTargetColor()
       {
           if (targetColor1 != null)
           {
               lerpAmount = Mathf.Clamp(lerpAmount + Time.deltaTime * speed, 0f, 1f);
               GetComponent<Renderer>().material.SetColor("_BaseColor",  Color.Lerp((Color) targetColor1, (Color) targetColor2, lerpAmount));
               if (lerpAmount >= 1f) { targetColor1 = null; }
               if (lerpAmount >= 1f) { targetColor2 = null; }
           }
       }
   
       void OnTriggerEnter(Collider collider)
       {
          if (collider.CompareTag(colliderTag))
          {
              SetNewTargetColor1(startColor);
              SetNewTargetColor2(endColor);
           }
       }
   
       void OnTriggerExit(Collider collider)
       {
           if (collider.CompareTag(colliderTag))
           {
              SetNewTargetColor1(endColor);
              SetNewTargetColor2(startColor);
           }
       }
   
      void SetNewTargetColor1(Color color1)
      {
          lerpAmount = 0f;
          targetColor1 = color1;
      }
      void SetNewTargetColor2(Color color2)
      {
          lerpAmount = 0f;
          targetColor2 = color2;
      }
   
   }




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 JPhilipp · Mar 15, 2020 at 11:29 AM 0
Share

@cublai Replace GetComponent<Renderer>().material.SetColor(...) with material.SetColor(...) for better performance -- it is suggested to not call GetComponent every frame, but to cache it into a reference (which is already assigned in Awake()).

avatar image
1

Answer by JPhilipp · Mar 14, 2020 at 05:40 PM

Some key points for your code:


  • Try not to use GetComponent every frame, it is not as performant. Store references to it once.

  • You don't really need to assign startTime. Time.time itself is good enough for most purposes, it contains the seconds since Unity starts.

  • CompareTag is safer as it checks string value issues on runtime instead of quietly failing.

  • The [SerializeField] attribute is more appropriate than making something public, at least if you want it to be inspector-settable only.

  • Values which never change can use const for extra clarity (and extra clues to the compiler, where needed).

  • OnTriggerStay runs all the time in the trigger collider. OnTriggerEnter however is more appropriate if you only want something to trigger once.

  • Outsource the actual lerping into another function called from Update, this guarantees it will continue running as needed.


Here's one way to do it. Note however there's also full libraries for tweening, like LeanTween, which might help you.


 using UnityEngine;
 
 public class ChangeColorOnTrigger : MonoBehaviour
 {
     [SerializeField] Color endColor;
     Color startColor;
 
     const float speed = 1f;
     const string colliderTag = "zone1";
 
     Color? targetColor = null;
     Material material = null;
     float lerpAmount = 0f;
        
     void Awake()
     {
         material = GetComponent<Renderer>().material;
         startColor = material.color;
     }
 
     void Update()
     {
         FollowTargetColor();
     }
 
     void FollowTargetColor()
     {
         if (targetColor != null)
         {
             lerpAmount = Mathf.Clamp(lerpAmount + Time.deltaTime * speed, 0f, 1f);
             material.color = Color.Lerp(material.color, (Color) targetColor, lerpAmount);
             if (lerpAmount >= 1f) { targetColor = null; }
         }
     }
 
     void OnTriggerEnter(Collider collider)
     {
        if (collider.CompareTag(colliderTag))
        {
            SetNewTargetColor(endColor);
         }
     }
 
     void OnTriggerExit(Collider collider)
     {
         if (collider.CompareTag(colliderTag))
         {
            SetNewTargetColor(startColor);
         }
     }
 
    void SetNewTargetColor(Color color)
    {
        lerpAmount = 0f;
        targetColor = color;
    }
 
 }
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 cublai · Mar 14, 2020 at 07:52 PM 0
Share

dont know why, but it does not do anything :/

avatar image cublai · Mar 14, 2020 at 08:35 PM 0
Share

Could you please show me how to reset the lerp so it starts from the startColor everytime it hits the Trigger?

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

128 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 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 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 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

Controlling duration of Color.Lerp in seconds 2 Answers

Color lerp once? 2 Answers

Distribute terrain in zones 3 Answers

Time.deltaTime making color lerp appear fast, but won't reach 1 1 Answer

Smooth gradient between colours? 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