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 Naphier · Aug 24, 2015 at 11:23 PM · editor-scriptingsharedmaterial

Instantiating material due to calling renderer.material during edit mode HELP!

Hi folks, Sorry for seemingly duplicating this question, but I'm not getting anywhere with the answers I'm finding. This project I'm working on is super old and the scripts are a horrendous mess. Now I get to fix it! If I switch to sharedMaterial then I get errors that it is a null obj ref. Also the materials tend to disappear in edit mode.

Can someone please take a look at this script and give me some hints on where to start making the modifications? Thanks!!

 using UnityEngine;
 using System.Collections;
 
 [ExecuteInEditMode]
 public class TextureComponent : MonoBehaviour
 {
     public ShaderType _shaderType = ShaderType.AlphaBlended;
     public string _texture;
     public float alpha=0;
 
     public bool _enabled = true;
     public bool _affectObjectPositionDependingOnResolution = false;
     public bool _affectObjectScaleDependingOnResolution = false;
     public float u1 = 0f;
     public float v1 = 0f;
     public float u2 = 1f;
     public float v2 = 1f;
 
     public  float uvWidth;
     public float uvHeight;
     
     private bool tempTextureLoaded = false;
     
     bool alphaAnimation=false;
     float toAlphaValue=0;
     float fromAlphaValue=0;
     float alphaAnimSpeed=0;
     public bool changeColor;
     public Color mainColor;
     
     
     public bool addToBatching =  false;
     
     public enum ShaderType
     {
         AlphaBlended,
         Multiply,
         Diffuse,
         TransparentDiffuse,
         UseOriginal
     }
 
     private Material GetMaterial()
     {
         Renderer r = GetComponent<Renderer>();
         if (r == null)
         {
             Debug.LogError("Renderer not found on " + gameObject.name);
             this.enabled = false;
             return null;
         }
         
         return r.material;
     }
 
     private void SetMaterial(Material mat)
     {
         GetComponent<Renderer>().material = mat;
     }
 
     private void SetMaterialtexture(Texture tex)
     { 
     
     }
 
     private void SetMaterialColor(Color color)
     {
 
     }
 
     private void SetMaterialTextureScale(float w, float h)
     {
 
     }
 
     private void SetMaterialTextureOffset(float u, float v)
     {
 
     }
     
     void Start ()
     {
         if(addToBatching)    
         {
             SetMaterial(TextureComponentHelper._instance.AddToBatching(this));
         }
         else
         {
             LoadMaterialsAndTextures();
         }
         
         
         if (_affectObjectPositionDependingOnResolution) 
         {
             transform.localPosition = new Vector3(
                                                 ((float)transform.localPosition.x / (float)ResolutionAdjuster._instance._developmentWidth) * ResolutionAdjuster._instance._worldWidth,
                                                 ((float)transform.localPosition.y / (float)ResolutionAdjuster._instance._developmentHeight) * ResolutionAdjuster._instance._worldHeight,
                                                 transform.localPosition.z
                                                 );
         }
     
         if (_affectObjectScaleDependingOnResolution) 
         {
 
             transform.localScale = new Vector3(
                                             ((float)transform.localScale.x / (float)ResolutionAdjuster._instance._developmentWidth) * ResolutionAdjuster._instance._worldWidth,
                                             ((float)transform.localScale.y / (float)ResolutionAdjuster._instance._developmentHeight) * ResolutionAdjuster._instance._worldHeight,
                                             transform.localScale.z
                                             );
         } 
         
         
         if(_enabled == false)
         {
             Disable();
         }
         
 
     }
     
     void Update ()
     {
         if(alphaAnimation)
         {
             SetAlpha(alpha+(toAlphaValue-fromAlphaValue)*(Time.deltaTime/alphaAnimSpeed));
             
             if((toAlphaValue-fromAlphaValue) > 0)
             {
                 if(alpha>=toAlphaValue)
                 {
                     alphaAnimation=false;
                 }
             }
             else
             {
                 if(alpha<=toAlphaValue)
                 {
                     alphaAnimation=false;
                 }
             }
         }        
     }
     
     void OnApplicationQuit()
     {
         if(TextureComponentHelper._instance != null)
         {
             ScriptableObject.Destroy(TextureComponentHelper._instance);
         }
     }
     
     
     public Material LoadMaterialsAndTextures()
     {
         
         if(GetComponent<TextMesh>()==null )
         {
             if(_shaderType != ShaderType.UseOriginal)
             {
                 SetMaterial(new Material(GetShaderString(_shaderType)));
             }
                 
             if(_texture != "_dummy")                                                   // dont load a texture if the texture name provided is dummy
                 GetMaterial().mainTexture = (Texture)Resources.Load(_texture);
             
             if( changeColor )
                 GetMaterial().color = mainColor;
         }
         
         if (GetComponent<AnimationComponent> () == null && _texture != "") {
             uvWidth = u2 - u1; 
             uvHeight = v2 - v1;
             SetMeterialScaleAndOffset(uvWidth, uvHeight, u1, v2);
         }
         
     
         return GetMaterial();
 
     }
 
     public void SetMeterialScaleAndOffset(float uvWidth , float uvHeight , float u1 , float v2)
     {
         GetMaterial().mainTextureScale = new Vector2(uvWidth, uvHeight);
         GetMaterial().mainTextureOffset = new Vector2(u1, 1 - v2);
     }
 
     
     public void ChangeTexture (string _tex)
     {
         if (_texture != _tex) {
             _texture = _tex;
             GetMaterial().mainTexture = (Texture)Resources.Load (_tex);
             
             uvWidth = u2 - u1; 
             uvHeight = v2 - v1;
 
             SetMeterialScaleAndOffset(uvWidth, uvHeight, u1, v2);
         }
     }
 
     public void ChangeTexture (string _tex, float _u1, float _v1, float _u2, float _v2)
     {
         if (_texture != _tex) {
             _texture = _tex;
             GetComponent<Renderer>().material.mainTexture = (Texture)Resources.Load (_tex);
             
             u1 = _u1;
             u2 = _u2;
             
             v1 = _v1;
             v2 = _v2;
             
             uvWidth = u2 - u1; 
             uvHeight = v2 - v1;
             SetMeterialScaleAndOffset(uvWidth, uvHeight, u1, v2);
         }
     }
     
     public void ChangeTexture (Texture2D _tex)
     {
         GetComponent<Renderer>().material.mainTexture = _tex;    
         uvWidth = u2 - u1; 
         uvHeight = v2 - v1;
         SetMeterialScaleAndOffset(uvWidth, uvHeight, u1, v2);
     }
     
     public void ChangeTemporaryTexture (string _path, string _name)                   // call when the file is not directly under the resources folder.
     {
         if (GetComponent<Renderer>().material.mainTexture.name.ToLower () != _name.ToLower () && _name != "") {
             GetComponent<Renderer>().material.mainTexture = (Texture)Resources.Load ((_path == "") ? _name : _path + "//" + _name);           // checks if the path is null        
             tempTextureLoaded = true;
         }
     }
     
     public void ChangeTemporaryTexture (string _path, string _name, float _u1, float _v1, float _u2, float _v2)                   // call when the file is not directly under the resources folder.
     {
         if (GetComponent<Renderer>().material.mainTexture.name.ToLower () != _name.ToLower () && _name != "") {
             GetComponent<Renderer>().material.mainTexture = (Texture)Resources.Load ((_path == "") ? _name : _path + "//" + _name);           // checks if the path is null        
             
             u1 = _u1;
             u2 = _u2;
             
             v1 = _v1;
             v2 = _v2;
             
             uvWidth = u2 - u1; 
             uvHeight = v2 - v1;
             SetMeterialScaleAndOffset(uvWidth, uvHeight, u1, v2);            
             tempTextureLoaded = true;
         }
     }
 
     public void ChangeTemporaryTexture (string _name)                                // call when the file is directly inside the resources folder.
     {
         if (GetComponent<Renderer>().material.mainTexture.name.ToLower () != _name.ToLower () && _name != "") {            // toLower aint that slow
             GetComponent<Renderer>().material.mainTexture = (Texture)Resources.Load (_name);
             tempTextureLoaded = true;
         }
     }
     
     public void LoadOriginalTexture ()                                               // load back the original texture.
     {
         if( _texture == "")
             return;
         if (GetComponent<Renderer>().material.mainTexture == null || tempTextureLoaded)
             
             GetComponent<Renderer>().material.mainTexture = (Texture)Resources.Load (_texture);
     }
     
     public void ChangeUV(float _u1,float _v1,float _u2, float _v2)
     {
         u1 = _u1;
         u2 = _u2;
             
         v1 = _v1;
         v2 = _v2;
             
         uvWidth = u2 - u1; 
         uvHeight = v2 - v1;
         SetMeterialScaleAndOffset(uvWidth, uvHeight, u1, v2);
     }
     
     public void ChangeUV(float _u2,float _v2)
     {
         u1=_u2-uvWidth;
         v1=_v2-uvHeight;
         u2=_u2;
         v2=_v2;
         SetMeterialScaleAndOffset(uvWidth, uvHeight, u1, v2);
     }
     
     
     public void SetAlpha(float _a)
     {
         alpha=_a;        
         GetComponent<Renderer>().material.SetColor("_TintColor",new Color(1,1,1,alpha));
     }
     
     public void SetColor(Color _color)
     {
         GetComponent<Renderer>().material.color = _color;
     }
     
     public void AnimateAlphaTo(float _a, float speed)
     {
         fromAlphaValue=alpha;
         toAlphaValue=_a;
         
         alphaAnimSpeed = speed;
         alphaAnimation=true;
     }
     
 
     public void Disable(bool showRenderer=false)
     {
         GetComponent<Renderer>().enabled = showRenderer;
         
         _enabled = false;
     }
     
     public void Enable ()
     {
         GetMaterial();
         GetComponent<Renderer>().enabled = true;
         _enabled = true;
     }
     
     void  OnDisable ()
     {
         if(GetComponent<Renderer>().material != null && !addToBatching)
             GetComponent<Renderer>().material.mainTexture = null;
     }
     
     void OnEnable ()
     {
         LoadOriginalTexture ();
     }
     
     public Color GetColorAt(Vector2 _cord)
     {
         
         return (GetComponent<Renderer>().material.mainTexture as Texture2D).GetPixelBilinear(_cord.x,_cord.y);
         
     }
     
     private static Shader GetShaderString(ShaderType _type)
     {
         Shader _shader = new Shader();
         switch (_type)
         {
             case ShaderType.AlphaBlended:
                 _shader = Shader.Find("Mobile/Particles/Alpha Blended");
             break;
             
             case ShaderType.Diffuse:
                 _shader = Shader.Find("Diffuse");
             break;
             
             case ShaderType.Multiply:
                 _shader = Shader.Find("Particles/Multiply");
             break;
             
             case ShaderType.TransparentDiffuse:
                 _shader = Shader.Find("Transparent/Diffuse");
             break;
 
             default:
                 _shader = Shader.Find("Diffuse");
                 Debug.LogError("Shader type undefined using diffuse");
             break;
         }
         
         return _shader;
     }
 
 }
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 LessThanEpic · Aug 25, 2015 at 03:29 AM 0
Share

$$anonymous$$ore info would be helpful. What is null when you change it to shared$$anonymous$$aterial?

avatar image Naphier · Aug 25, 2015 at 04:52 AM 0
Share

I think I've got it. Not sure why the null ref was happening. I cleared it out and now have the script working without spam$$anonymous$$g the material instantiation error. I'll post here when I'm finished cleaning it up.

0 Replies

· Add your reply
  • Sort: 

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

26 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

Related Questions

Custom Inspector to Load Instance Values 0 Answers

Custom editor, serialize and prefab issue 0 Answers

Working in SceneView 0 Answers

BuildPlayer in Editor script throwing an error 0 Answers

Find PlayerSettings Architecture (iOS) from Script 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