SetColor() public method

Set a named color value.

public SetColor ( int nameID, Color color ) : void
nameID int Property name ID, use Shader.PropertyToID to get it.
color Color Color value to set.
return void
Example #1
0
	void Start () {

		if(PlayerPrefs.GetInt(Application.loadedLevelName + "Door" + id) == 0){
			open = false;
		}else{
			open = true;
		}

		mat = GetComponent<MeshRenderer>().material;

		if(bodenschalter.Length == 1){
			onColor = bodenschalter[0].onColor;
			offColor = bodenschalter[0].offColor;
		}

		if(open){
			mat.SetColor("_Color", onColor);
		}else{
			mat.SetColor("_Color", offColor);
		}

		switch(openDirection){
			case DoorDirection.UP: endpos = transform.position + transform.up*openDistance*5.5f; break;
			case DoorDirection.DOWN: endpos = transform.position - transform.up*openDistance*5.5f; break;
			case DoorDirection.LEFT: endpos = transform.position - transform.right*openDistance*5.5f; break;
			case DoorDirection.FWD: endpos = transform.position + transform.forward*openDistance*5.5f; break;
			case DoorDirection.BWD: endpos = transform.position - transform.forward*openDistance*5.5f; break;
			default: endpos = transform.position + transform.right*openDistance*5.5f; break;
		}

		startpos = transform.position;
	
	}
Example #2
0
 void Awake()
 {
     material = new Material(Shader.Find("Hidden/ChannelMixer"));
     material.SetColor("_R", RGB[0, 0]);
     material.SetColor("_G", RGB[0, 1]);
     material.SetColor("_B", RGB[0, 2]);
 }
    void Start()
    {
        var granny = GameObject.Find("Granny");

        if (granny != null)
        {
            grannyCollider = granny.GetComponent<Collider2D>();
            itemUse = granny.GetComponent<ItemUse>();
        }

        var spriteRenderer = GetComponent<SpriteRenderer>();

        if (materials == null)
        {
            var effectsCount = Enum.GetNames(typeof(Effect)).Length;

            materials = new Material[effectsCount];

            materials[0] = spriteRenderer.material;

            for (int i = 1; i < effectsCount; i++)
            {
                var randomMaterial = new Material(spriteRenderer.material);

                randomMaterial.SetColor("_ColorR", Utils.RandomHueColor());
                randomMaterial.SetColor("_ColorG", Utils.RandomHueColor());
                randomMaterial.SetColor("_ColorB", Color.white);

                materials[i] = randomMaterial;
            }
        }

        spriteRenderer.material = getMaterial(PillEffect);
    }
Example #4
0
    //ball is destoryed because it got stuck in the wall
    void BallDestroy()
    {
        Material particleColor = new Material(shotColor);
        if (colorShot == 0)//if ball is green increase greenshots by one
        {
            gVar.greenShots++;
            particleColor.SetColor("_EmissionColor", GREEN);
        }
        else if (colorShot == 1)
        {
            gVar.redShots++;
            particleColor.SetColor("_EmissionColor", RED);
        }
        else if (colorShot == 2)
        {
            gVar.blueShots++;
            particleColor.SetColor("_EmissionColor", BLUE);
        }
        else if (colorShot == 3)
        {
            gVar.purpleShots++;
            particleColor.SetColor("_EmissionColor", PURPLE);
        }

        GameObject particles = (GameObject)Instantiate(ballParticleSystem, this.GetComponent<Transform>().position, Quaternion.identity);
        particles.GetComponent<Renderer>().material = particleColor;
        Destroy(particles, 0.5f);
        Destroy(gameObject);
    }
Example #5
0
 void Awake()
 {
     material = new Material( Shader.Find("Hidden/Gradient") );
     material.SetColor("_ColorA", colorA);
     material.SetColor("_ColorB", colorB);
     material.SetColor("_ColorC", colorC);
 }
	private void GenerateWireframeMeshsAndMaterials() {
		foreach (MeshNMaterial subObj in subObjects) {
			//添加AmazingWireframeGenerator
			subObj.gameObject.AddComponent<TheAmazingWireframeGenerator>();
			for (int i = 0;i < subObj.originalMaterials.Length;i++) {
				Material wireframeNoTexMat = new Material(
					Shader.Find("VacuumShaders/The Amazing Wireframe/Unlit/NoTex"));
				wireframeNoTexMat.SetColor("_Color", subObj.originalMaterials[i].GetColor("_Color"));
				wireframeNoTexMat.EnableKeyword("V_WIRE_ANTIALIASING_ON");
				wireframeNoTexMat.EnableKeyword("V_WIRE_LIGHT_ON");
				subObj.wireframeNoTexMaterials[i] = wireframeNoTexMat;
				Material wireframeTexMat = new Material(
						Shader.Find("VacuumShaders/The Amazing Wireframe/Deferred/Bumped Specular"));
				wireframeTexMat.SetColor("_Color", subObj.originalMaterials[i].GetColor("_Color"));
				if (subObj.originalMaterials[i].HasProperty("_SpecColor"))
					wireframeTexMat.SetColor("_SpecColor", subObj.originalMaterials[i].GetColor("_SpecColor"));
				if (subObj.originalMaterials[i].HasProperty("_Shininess"))
					wireframeTexMat.SetFloat("_Shininess", subObj.originalMaterials[i].GetFloat("_Shininess"));
				wireframeTexMat.SetTexture("_MainTex", subObj.originalMaterials[i].GetTexture("_MainTex"));
				if (subObj.originalMaterials[i].HasProperty("_BumpMap"))
					wireframeTexMat.SetTexture("_BumpMap", subObj.originalMaterials[i].GetTexture("_BumpMap"));
				wireframeTexMat.EnableKeyword("V_WIRE_ANTIALIASING_ON");
				wireframeTexMat.EnableKeyword("V_WIRE_LIGHT_ON");
				subObj.wireframeTexMaterials[i] = wireframeTexMat;
			}
		}
	}
        public PathController(QueryTool tool)
        {
            queryTool = tool;
            currentHighlightType = HighlightType.None;

            Config.instance.eventConfigChanged += () => { OnConfigChanged(); };

            Log.info("Load Line Material...");

            Color red = new Color(1, 0, 0);
            Color gold = new Color(1, 0.9f, 0);

            string lineShader = ResourceLoader.loadResourceString("Materials/Shaders/TransparentVertexLit.shader");

            lineMaterial = new Material(lineShader);
            lineMaterial.color = red;
            lineMaterial.SetColor("_Emission", red);
            lineMaterial.SetColor("_SpecColor", Color.black); //Disable shine effect
            lineMaterial.mainTexture = ResourceLoader.loadTexture("Materials/NewSkin.png");
            lineMaterial.renderQueue = 100;

            lineMaterialHighlight = new Material(lineMaterial);
            lineMaterialHighlight.color = gold;
            lineMaterialHighlight.SetColor("_Emission", gold);
            lineMaterial.renderQueue = 101;

            Texture pin = ResourceLoader.loadTexture("Materials/Pin.png");

            activeSegmentIndicator = Billboard.Create(Billboard.CreateSpriteMaterial(pin, Color.green));
            vehicleIndicator = Billboard.CreateSpriteMaterial(pin, red);
            vehicleIndicatorHighlight = Billboard.CreateSpriteMaterial(pin, gold);

            Log.debug("PathController initialized");
        }
Example #8
0
	IEnumerator Test( Material mat, Color newColor )
	{
		Color orgColor = mat.GetColor("_EmissionColor");
		mat.SetColor("_EmissionColor", newColor);
		yield return new WaitForSeconds(0.5f);
		mat.SetColor("_EmissionColor", orgColor);
	}
Example #9
0
    // Use this for initialization
    void Start()
    {
        //countdown = transform.parent.parent.GetComponent<Countdown>();

        countdown = transform.parent.GetComponent<Countdown>();

        renderer = GetComponent<Renderer>();
        material = renderer.material;

        if (red) {
            material.SetColor("_EmissionColor", Color.grey);
            myColor = Color.red;
            signal = Countdown.signal.RED;
        }
        if (yellow) {
            material.SetColor("_EmissionColor", Color.grey);
            myColor = Color.yellow;
            signal = Countdown.signal.YELLOW;
        }
        if (green) {
            material.SetColor("_EmissionColor", Color.grey);
            myColor = Color.green;
            signal = Countdown.signal.GREEN;
        }
        material.SetFloat("_EmissionScaleUI", 0.1f);
    }
    /// <summary>
    /// Changes the color of the given material
    /// </summary>
    /// <param name="material"></param>
    /// <param name="color"></param>
    public IEnumerator ChangeColor(Material material, Color color, float seconds)
    {
        Color currentColor = material.GetColor("_EmissionColor");
        material.SetColor("_EmissionColor", color);
        yield return new WaitForSeconds(seconds);

        // Reset color to initial one
        if (seconds > 0) { material.SetColor("_EmissionColor", currentColor); }
    }
 public void Start()
 {
     fxRes = GetComponent<IndieEffects>();
     mat = new Material(shader);
     mat.SetColor("_Lift", Lift);
     mat.SetFloat("_LiftB", Mathf.Clamp(LiftBright, 0f, 2f));
     mat.SetColor("_Gamma", Gamma);
     mat.SetFloat("_GammaB", Mathf.Clamp(GammaBright, 0f, 2f));
     mat.SetColor("_Gain", Gain);
     mat.SetFloat("_GainB", Mathf.Clamp(GainBright, 0f, 2f));
 }
Example #12
0
	// Update is called once per frame
	IEnumerator attackobject() {
        yield return new WaitForEndOfFrame();
       mat = transform.GetChild(0).gameObject.GetComponent<MeshRenderer>().material;
        while (true)
        {
            mat.SetColor("_TintColor",new Color(0.3f,0.3f,0.3f));
            yield return new WaitForSeconds(Random.value/10);
            mat.SetColor("_TintColor", new Color(0.5f, 0.5f, 0.5f));
            yield return new WaitForSeconds(Random.value);
        }
	
	}
        private void ConfigMaterial(MmdMaterial mmdMaterial, MmdUnityConfig config, UnityEngine.Material material, Texture mainTexture)
        {
            material.SetColor("_Color", mmdMaterial.DiffuseColor);
            material.SetFloat("_Opacity", mmdMaterial.DiffuseColor.a);
            material.SetColor("_AmbColor", mmdMaterial.AmbientColor);
            material.SetColor("_SpecularColor", mmdMaterial.SpecularColor);
            material.SetFloat("_Shininess", mmdMaterial.Shiness);
            material.SetFloat("_OutlineWidth", mmdMaterial.EdgeSize);
            material.SetColor("_OutlineColor", mmdMaterial.EdgeColor);
            if (mainTexture != null)
            {
                material.mainTexture      = mainTexture;
                material.mainTextureScale = new Vector2(1, 1);
            }


            if (mmdMaterial.SubTextureType != MmdMaterial.SubTextureTypeEnum.MatSubTexOff)
            {
                var additionalTexture =
                    mmdMaterial.SubTexture == null ? null : _textureLoader.LoadTexture(mmdMaterial.SubTexture);
                if (additionalTexture != null)
                {
                    additionalTexture.wrapMode = TextureWrapMode.Clamp;
                    switch (mmdMaterial.SubTextureType)
                    {
                    case MmdMaterial.SubTextureTypeEnum.MatSubTexSpa:
                        material.SetTexture("_SphereAddTex", additionalTexture);
                        material.SetTextureScale("_SphereAddTex", new Vector2(1, 1));
                        break;

                    case MmdMaterial.SubTextureTypeEnum.MatSubTexSph:
                        material.SetTexture("_SphereMulTex", additionalTexture);
                        material.SetTextureScale("_SphereMulTex", new Vector2(1, 1));
                        break;
                    }
                }
            }

            RefreshShaderKeywords(mmdMaterial, config, material);

            var toonTexture = _textureLoader.LoadTexture(mmdMaterial.Toon);

            if (toonTexture != null)
            {
                toonTexture.wrapMode = TextureWrapMode.Clamp;
                material.SetTexture("_ToonTex", toonTexture);
                material.SetTextureScale("_ToonTex", new Vector2(1, 1));
            }
        }
 protected IEnumerator _FadeOut(Material m, float time)
 {
     var c = m.GetColor(Outline);
     var startAlpha = c.a;
     var start = Time.time;
     var end = start + time;
     while(Time.time <= end) {
         var progress = Mathf.InverseLerp(start, end, Time.time);
         var alpha = Mathf.Lerp(startAlpha, 0, progress);
         m.SetColor(Outline, SetAlpha(c, alpha));
         yield return new WaitForEndOfFrame();
     }
     m.SetColor(Outline, SetAlpha(c, 0));
     _fadingOut.Remove(m);
 }
Example #15
0
    //fades the buttons in as well
    IEnumerator FadeIn(Material material, float fadeSpeed)
    {
        Color tempColor = material.color;
          tempColor.a = 0;
          material.SetColor ("_Color", tempColor);

          while (material.color.a < 1) {

        tempColor.a += fadeSpeed;
        material.SetColor ("_Color", tempColor);

        yield return null;

          }
    }
Example #16
0
	void Start () {

		mat = GetComponentInChildren<MeshRenderer>().material;

		if(bodenschalter.Length > 0){
			onColor = bodenschalter[0].onColor;
			offColor = bodenschalter[0].offColor;
		}

		if(on){
			mat.SetColor("_Color", onColor);
		}else{
			mat.SetColor("_Color", offColor);
		}
	}
Example #17
0
    /// <summary>
    ///
    /// </summary>
    void Update()
    {
        // editor force show
        if (m_ForceShow)
        {
            Show();
        }
        else
        {
            // always fade out muzzleflash if it is visible
            if (m_Color.a > 0.0f)
            {
                m_Color.a -= m_FadeSpeed * (Time.deltaTime * 60.0f);
                if (m_Light != null)
                {
                    m_Light.intensity = m_LightIntensity * (m_Color.a * 2.0f);                          // sync light intensity to muzzleflash alpha
                }
            }
        }

        if (m_Material != null)
        {
            m_Material.SetColor("_TintColor", m_Color);                 // // TODO:will affect all muzzleflashes using this material in the scene (!)
        }
        if (m_Color.a < 0.01f)
        {
            m_Renderer.enabled = false;
            if (m_Light != null)
            {
                m_Light.enabled = false;
            }
        }
    }
Example #18
0
 public void SetCurrentToTo()
 {
     if (_material = material)
     {
         _material.SetColor(propertyID, to);
     }
 }
Example #19
0
 public void SetCurrentToFrom()
 {
     if (_material = material)
     {
         _material.SetColor(propertyID, from);
     }
 }
        void LateUpdate()
        {
            var mouse = Mouse.current;

            if (Cam == null || mouse == null || !mouse.leftButton.wasPressedThisFrame)
            {
                return;
            }

            var position         = new Vector3(mouse.position.x.ReadValue(), mouse.position.y.ReadValue());
            var screenPointToRay = Cam.ScreenPointToRay(position);
            var rayInput         = new RaycastInput
            {
                Start  = screenPointToRay.origin,
                End    = screenPointToRay.GetPoint(RAYCAST_DISTANCE),
                Filter = CollisionFilter.Default
            };

            if (!physicsWorld.CastRay(rayInput, out RaycastHit hit))
            {
                return;
            }

            var selectedEntity = physicsWorld.Bodies[hit.RigidBodyIndex].Entity;
            var renderMesh     = entityManager.GetSharedComponentData <RenderMesh>(selectedEntity);
            var mat            = new UnityEngine.Material(renderMesh.material);

            mat.SetColor("_BaseColor", UnityEngine.Random.ColorHSV());
            renderMesh.material = mat;

            entityManager.SetSharedComponentData(selectedEntity, renderMesh);
        }
 public override void Restore()
 {
     if (null == m_Material)
     {
         return;
     }
     // end if
     if (!string.IsNullOrEmpty(m_property))
     {
         m_Material.SetColor(m_property, m_beginColor);
     }
     else if (m_propertyID != -1)
     {
         m_Material.SetColor(m_propertyID, m_beginColor);
     } // end if
 }
Example #22
0
 static public int SetColor(IntPtr l)
 {
     try {
         int argc = LuaDLL.lua_gettop(l);
         if (matchType(l, argc, 2, typeof(int), typeof(UnityEngine.Color)))
         {
             UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
             System.Int32         a1;
             checkType(l, 2, out a1);
             UnityEngine.Color a2;
             checkType(l, 3, out a2);
             self.SetColor(a1, a2);
             pushValue(l, true);
             return(1);
         }
         else if (matchType(l, argc, 2, typeof(string), typeof(UnityEngine.Color)))
         {
             UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
             System.String        a1;
             checkType(l, 2, out a1);
             UnityEngine.Color a2;
             checkType(l, 3, out a2);
             self.SetColor(a1, a2);
             pushValue(l, true);
             return(1);
         }
         pushValue(l, false);
         LuaDLL.lua_pushstring(l, "No matched override function to call");
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
    public IEnumerator PlayLaserEffect(float effectDuration, Vector3 impactPos)
    {
        #if FULL_DEBUG
        if(!laser)
        {
            Debug.LogError("Line renderer null");
        }
        #endif
        laser.SetPosition(0, transform.position);
        laser.SetPosition(1, impactPos);
        float distance = Vector3.Distance(transform.position, impactPos);
        renderer.materials[0].mainTextureScale.Set(distance / uvLength, renderer.materials[0].mainTextureScale.y) ;
        mat = laser.renderer.material;

        float currentTime = 0.0f;
        while(currentTime<=1.0f)
        {
            //lerp colour
            mat.SetColor("_TintColor", Color.Lerp(startColour, endColour, currentTime));
            //lerp size
            float newSize = Mathf.Lerp(startWidth, endWidth, currentTime);
            laser.SetWidth(newSize, newSize);
            currentTime += Time.deltaTime / effectDuration;
            yield return null;
        }
    }
Example #24
0
        IEnumerator Grow()
        {
            float f = 0;
            float t = 0;
            Vector3 originalScale = transform.localScale;
            Vector3 targetScale = originalScale * EndScale;
            Material originalMaterial = new Material(renderer.material);
            Color originalColor = originalMaterial.GetColor("_TintColor");
            Color targetColor = new Color(originalColor.r, originalColor.g, originalColor.b, 0F);
            renderer.material = originalMaterial;

            while (f <= duration)
            {
                t = f / duration;
                transform.localScale = Vector3.Lerp(originalScale, targetScale, t);

                originalMaterial.SetColor("_TintColor", Color.Lerp(originalColor, targetColor, t));

                f += Time.deltaTime;
                yield return new WaitForEndOfFrame();
            }

            if (mode == FXmode.DestroyAtEnd)
                Destroy(gameObject);

            else if (mode == FXmode.Loop)
                Play();
        }
    // Use this for initialization
    void Start()
    {
        hold = GetComponent<Renderer>().material;

        plCol = (gameMan = GameObject.FindGameObjectWithTag("Manager").GetComponent<GameManager>()).pColor[playerNum];
        hold.SetColor("_Color", plCol + (Color.white * .2f));
    }
Example #26
0
 // Use this for initialization
 void Start()
 {
     mat = GetComponent<Renderer> ().material;
     mat.SetColor ("_EnergyColor", energyColor);
     mat.SetFloat ("_Visibility", visibility);
     mat.SetFloat ("_CollisionTime", -99f); // To ensure that animation is already "over" by the time we start.
 }
Example #27
0
    /// <summary>
    /// 
    /// </summary>
    /// <param name="lineMaterial"></param>
    /// <param name="color"></param>
    /// <param name="source"></param>
    /// <param name="destination"></param>
    public static void BoxDrawing(Material lineMaterial, Color color, float width, float height, Vector3 position)
    {
        lineMaterial.SetColor("_TintColor", color);
        lineMaterial.SetPass(0);

        GL.Begin(GL.LINES);

        // upper width line
        GL.Vertex3(position.x - width / 2, position.y, position.z + height / 2);
        GL.Vertex3(position.x + width / 2, position.y, position.z + height / 2);

        // right height line
        GL.Vertex3(position.x + width / 2, position.y, position.z + height / 2);
        GL.Vertex3(position.x + width / 2, position.y, position.z - height / 2);

        // lower width line
        GL.Vertex3(position.x + width / 2, position.y, position.z - height / 2);
        GL.Vertex3(position.x - width / 2, position.y, position.z - height / 2);

        //height lines
        GL.Vertex3(position.x - width / 2, position.y, position.z - height / 2);
        GL.Vertex3(position.x - width / 2, position.y, position.z + height / 2);

        GL.End();
    }
        /// <summary>
        /// Copy Shader properties from source to destination material.
        /// </summary>
        /// <param name="source"></param>
        /// <returns></returns>
        public static void CopyMaterialProperties(Material source, Material destination)
        {
            MaterialProperty[] source_prop = MaterialEditor.GetMaterialProperties(new Material[] { source });

            for (int i = 0; i < source_prop.Length; i++)
            {
                int property_ID = Shader.PropertyToID(source_prop[i].name);
                if (destination.HasProperty(property_ID))
                {
                    //Debug.Log(source_prop[i].name + "  Type:" + ShaderUtil.GetPropertyType(source.shader, i));
                    switch (ShaderUtil.GetPropertyType(source.shader, i))
                    {
                        case ShaderUtil.ShaderPropertyType.Color:
                            destination.SetColor(property_ID, source.GetColor(property_ID));                          
                            break;
                        case ShaderUtil.ShaderPropertyType.Float:
                            destination.SetFloat(property_ID, source.GetFloat(property_ID));
                            break;
                        case ShaderUtil.ShaderPropertyType.Range:
                            destination.SetFloat(property_ID, source.GetFloat(property_ID));
                            break;
                        case ShaderUtil.ShaderPropertyType.TexEnv:
                            destination.SetTexture(property_ID, source.GetTexture(property_ID));
                            break;
                        case ShaderUtil.ShaderPropertyType.Vector:
                            destination.SetVector(property_ID, source.GetVector(property_ID));
                            break;
                    }
                }
            }

        }
 public override void AssignNewShaderToMaterial(Material material, Shader oldShader, Shader newShader)
 {
     if (material.HasProperty("_Emission"))
     {
         material.SetColor("_EmissionColor", material.GetColor("_Emission"));
     }
     base.AssignNewShaderToMaterial(material, oldShader, newShader);
     if ((oldShader == null) || !oldShader.name.Contains("Legacy Shaders/"))
     {
         SetupMaterialWithBlendMode(material, (BlendMode) ((int) material.GetFloat("_Mode")));
     }
     else
     {
         BlendMode opaque = BlendMode.Opaque;
         if (oldShader.name.Contains("/Transparent/Cutout/"))
         {
             opaque = BlendMode.Cutout;
         }
         else if (oldShader.name.Contains("/Transparent/"))
         {
             opaque = BlendMode.Fade;
         }
         material.SetFloat("_Mode", (float) opaque);
         Material[] mats = new Material[] { material };
         this.DetermineWorkflow(MaterialEditor.GetMaterialProperties(mats));
         MaterialChanged(material, this.m_WorkflowMode);
     }
 }
	// Use this for initialization
	void Start ()
    {
        holder = new GameObject();
        holder.transform.parent = this.transform;
        holder.transform.localPosition = Vector3.zero;

        pointer = GameObject.CreatePrimitive(PrimitiveType.Cube);
        pointer.transform.parent = holder.transform;
        pointer.transform.localScale = new Vector3(thickness, thickness, 100f);
        pointer.transform.localPosition = new Vector3(0f, 0f, 50f);
        BoxCollider collider = pointer.GetComponent<BoxCollider>();
        if (addRigidBody)
        {
            if (collider)
            {
                collider.isTrigger = true;
            }
            Rigidbody rigidBody = pointer.AddComponent<Rigidbody>();
            rigidBody.isKinematic = true;
        }
        else
        {
            if(collider)
            {
                Object.Destroy(collider);
            }
        }
        Material newMaterial = new Material(Shader.Find("Unlit/Color"));
        newMaterial.SetColor("_Color", color);
        pointer.GetComponent<MeshRenderer>().material = newMaterial;
	}
        void LateUpdate()
        {
            if (!Input.GetMouseButtonDown(0) || Cam == null)
            {
                return;
            }

            var screenPointToRay = Cam.ScreenPointToRay(Input.mousePosition);
            var rayInput         = new RaycastInput
            {
                Start  = screenPointToRay.origin,
                End    = screenPointToRay.GetPoint(RAYCAST_DISTANCE),
                Filter = CollisionFilter.Default
            };

            if (!physicsWorld.CastRay(rayInput, out RaycastHit hit))
            {
                return;
            }

            var selectedEntity = physicsWorld.Bodies[hit.RigidBodyIndex].Entity;
            var renderMesh     = entityManager.GetSharedComponentData <RenderMesh>(selectedEntity);
            var mat            = new UnityEngine.Material(renderMesh.material);

            mat.SetColor("_Color", UnityEngine.Random.ColorHSV());
            renderMesh.material = mat;

            entityManager.SetSharedComponentData(selectedEntity, renderMesh);
        }
Example #32
0
    /// <summary>
    /// Draws a circle thingy.
    /// </summary>
    /// <param name="lineMaterial">The line material.</param>
    /// <param name="color">The color.</param>
    /// <param name="iteration">The iteration.</param>
    /// <param name="radius">The radius.</param>
    /// <param name="s">The s.</param>
    /// <param name="q">The q.</param>
    public static void CircleDrawing(Material lineMaterial, Color color, int iteration, float radius, Vector3 source, Quaternion rotatiom)
    {
        lineMaterial.SetColor("_TintColor", color);
        lineMaterial.SetPass(0);

        GL.Begin(GL.LINES);
        for (int i = 1; i <= iteration + 1; i++)
        {
            float dg = i;
            float n = iteration;

            Vector3 v = Vector3.zero;

            v.x = radius * Mathf.Cos((dg / n) * Mathf.PI * 2);
            v.z = radius * Mathf.Sin((dg / n) * Mathf.PI * 2);
            v = rotatiom * v;

            Vector3 v1 = new Vector3(v.x + source.x, v.y + source.y, v.z + source.z);

            GL.Vertex3(v1.x, v1.y, v1.z);

            if (i != 1 && i != iteration + 1)
            {
                GL.Vertex3(v.x + source.x, v.y + source.y, v.z + source.z);
            }
        }

        GL.End();
    }
Example #33
0
    float gr = (1.0f + Mathf.Sqrt(5.0f)) / 2.0f; //golen ratio (a+b is to a as a is to b)

    #endregion Fields

    #region Methods

    void Start()
    {
        Nose = GameObject.Find("Nose");
        Nose.AddComponent<MeshFilter>();
        Nose.AddComponent<MeshRenderer>();
        noseMesh = GetComponent<MeshFilter>().mesh;//attach mesh to nose
        noseMesh.Clear();

        noseMesh.vertices = new Vector3[] {//construct pyramid for nose
            new Vector3( gr,   		     1,		  	0),
            new Vector3( gr-1,    -gr*0.6f, -gr*0.75f),
            new Vector3( gr-1, 	  -gr*0.6f,  gr*0.75f),
            new Vector3( gr*1.5f, -gr*0.6f,   		0)};

        List<int> noseTrianglesIndices = new List<int>() {//arrange triangles
            0,  1,  2,
            0,  3,  1,
            0,  2,  3,
            1,  3,  2};
        noseMesh.triangles = noseTrianglesIndices.ToArray();

        //Set Colour
        Material material = new Material(Shader.Find("Standard"));
        Color fleshtone = new Color(10, 205, 180);
        material.SetColor("fleshtone", fleshtone);

        Nose.GetComponent<Renderer>().material = material;

        noseMesh.RecalculateBounds();
        noseMesh.RecalculateNormals();
        noseMesh.Optimize();
    }
    static int SetColor(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Material), typeof(int), typeof(UnityEngine.Color)))
            {
                UnityEngine.Material obj = (UnityEngine.Material)ToLua.ToObject(L, 1);
                int arg0 = (int)LuaDLL.lua_tonumber(L, 2);
                UnityEngine.Color arg1 = ToLua.ToColor(L, 3);
                obj.SetColor(arg0, arg1);
                return(0);
            }
            else if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Material), typeof(string), typeof(UnityEngine.Color)))
            {
                UnityEngine.Material obj = (UnityEngine.Material)ToLua.ToObject(L, 1);
                string            arg0   = ToLua.ToString(L, 2);
                UnityEngine.Color arg1   = ToLua.ToColor(L, 3);
                obj.SetColor(arg0, arg1);
                return(0);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Material.SetColor"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
Example #35
0
	protected void SetGenericMaterialProperty(Material destination, string property_name, object value)
	{
		try{

			ShaderUtil.ShaderPropertyType type = GetPropertyType(destination, property_name);
			switch(type)
			{
			case ShaderUtil.ShaderPropertyType.Color:
				destination.SetColor(property_name, value.UnityBridgeObjectToColor());
				break;
			case ShaderUtil.ShaderPropertyType.Range:
			case ShaderUtil.ShaderPropertyType.Float:
				destination.SetFloat(property_name, value.UnityBridgeObjectToFloat());
				break;
			case ShaderUtil.ShaderPropertyType.Vector:
				destination.SetVector(property_name, value.UnityBridgeObjectToVector());
				break;
			case ShaderUtil.ShaderPropertyType.TexEnv:
				destination.SetTexture(property_name, TextureManager.Instance.ResolveMap( destination.name + "_" + property_name, value));
				break;
			default:
				Debug.Log("Unknown shader type " + type.ToString());
				break;
			}

		}
		catch(KeyNotFoundException e)
		{
			Debug.Log(e.Message);
		}
	}
Example #36
0
    // Called by the camera to apply the image effect
    void OnRenderImage(RenderTexture source, RenderTexture destination)
    {
        if (!mat) {
            // Use the color detection shader
            var shader = Shader.Find ("Custom/ColorDetect");
            mat = new Material (shader);
            mat.hideFlags = HideFlags.HideAndDontSave;

            // Set up threshold and shading colors
            mat.SetColor("_ThresholdColor", thresholdColor);
            mat.SetColor("_ShadingColor", shadingColor);
        }

        //mat is the material containing your shader
        Graphics.Blit(source,destination,mat);
    }
Example #37
0
 static public int SetColor(IntPtr l)
 {
     try{
         if (matchType(l, 2, typeof(System.String), typeof(UnityEngine.Color)))
         {
             UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
             System.String        a1;
             checkType(l, 2, out a1);
             UnityEngine.Color a2;
             checkType(l, 3, out a2);
             self.SetColor(a1, a2);
             return(0);
         }
         else if (matchType(l, 2, typeof(System.Int32), typeof(UnityEngine.Color)))
         {
             UnityEngine.Material self = (UnityEngine.Material)checkSelf(l);
             System.Int32         a1;
             checkType(l, 2, out a1);
             UnityEngine.Color a2;
             checkType(l, 3, out a2);
             self.SetColor(a1, a2);
             return(0);
         }
         LuaDLL.luaL_error(l, "No matched override function to call");
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
 public static void Color(UnityEngine.Material material, string name, Color[] array)
 {
     for (int i = 0; i < array.Length; i++)
     {
         material.SetColor(name + i.ToString(), array[i]);
     }
 }
Example #39
0
 // Use this for initialization
 void Start()
 {
     myMaterial = gameObject.transform.Find("button").GetComponent<Renderer>().material;
     myMaterial.SetColor ("_Color", Color.green);
     cannonScript = GameObject.Find("Cannon").GetComponent<cannon>();
     Debug.Log ("cannonScript = " + cannonScript);
 }
Example #40
0
        public UnityEngine.Material CreateMaterial(PbrMaterial vpxMaterial, TableBehavior table, StringBuilder debug = null)
        {
            var unityMaterial = new UnityEngine.Material(GetShader())
            {
                name = vpxMaterial.Id
            };

            // apply some basic manipulations to the color. this just makes very
            // very white colors be clipped to 0.8204 aka 204/255 is 0.8
            // this is to give room to lighting values. so there is more modulation
            // of brighter colors when being lit without blow outs too soon.
            var col = vpxMaterial.Color.ToUnityColor();

            if (vpxMaterial.Color.IsGray() && col.grayscale > 0.8)
            {
                debug?.AppendLine("Color manipulation performed, brightness reduced.");
                col.r = col.g = col.b = 0.8f;
            }

            // alpha for color depending on blend mode
            ApplyBlendMode(unityMaterial, vpxMaterial.MapBlendMode);
            if (vpxMaterial.MapBlendMode == BlendMode.Translucent)
            {
                col.a = Mathf.Min(1, Mathf.Max(0, vpxMaterial.Opacity));
            }

            unityMaterial.SetColor(BaseColor, col);

            // validate IsMetal. if true, set the metallic value.
            // found VPX authors setting metallic as well as translucent at the
            // same time, which does not render correctly in unity so we have
            // to check if this value is true and also if opacity <= 1.
            if (vpxMaterial.IsMetal && (!vpxMaterial.IsOpacityActive || vpxMaterial.Opacity >= 1))
            {
                unityMaterial.SetFloat(Metallic, 1f);
                debug?.AppendLine("Metallic set to 1.");
            }

            // roughness / glossiness
            unityMaterial.SetFloat(Smoothness, vpxMaterial.Roughness);


            // map
            if (table != null && vpxMaterial.HasMap)
            {
                unityMaterial.SetTexture(BaseMap, table.GetTexture(vpxMaterial.Map.Name));
            }

            // normal map
            if (table != null && vpxMaterial.HasNormalMap)
            {
                unityMaterial.EnableKeyword("_NORMALMAP");

                unityMaterial.SetTexture(BumpMap, table.GetTexture(vpxMaterial.NormalMap.Name)
                                         );
            }

            return(unityMaterial);
        }
Example #41
0
    //public float Duration = 2.0f;
    void Update()
    {
        Renderer renderer = GetComponent <Renderer> ();

        UnityEngine.Material mat = renderer.material;
        float emission           = mini + Mathf.PingPong(Time.time * TimeMultiplier, maxi - mini);
        //float emission = Mathf.PingPong (Time.time, 1.0f);
        Color baseColor = Color.white;         //Replace this with whatever you want for your base color at emission level '1'

        Color finalColor = baseColor * Mathf.LinearToGammaSpace(emission);

        mat.SetColor("_EmissionColor", finalColor);
    }
    private UnityEngine.Material LoadMaterial(glTFLoader.Schema.Material material)
    {
        string techniqueID = material.Technique;

        if (techniqueID != null)
        {
            LoadTechnique(m_model.Techniques[techniqueID]);
        }

        UnityEngine.Material res = new UnityEngine.Material(UnityEngine.Shader.Find(" Diffuse"));
        res.name = material.Name;

        if (material.Values != null)
        {
            if (material.Values.ContainsKey("ambient"))
            {
                JArray ambientArray = material.Values["ambient"] as JArray;
                int[]  ambient      = ambientArray.ToObject <int[]>();
                res.SetColor("_Color", ArrayConverter.ToColor(ambient));
            }
            if (material.Values.ContainsKey("emission"))
            {
                JArray emissionArray = material.Values["emission"] as JArray;
                int[]  emission      = emissionArray.ToObject <int[]>();
                res.SetColor("_EmissionColor", ArrayConverter.ToColor(emission));
            }
            if (material.Values.ContainsKey("diffuse"))
            {
                if (material.Values["diffuse"] is string)
                {
                    string    diffuseTextureID = material.Values["diffuse"] as string;
                    Texture2D texture          = LoadTexture(m_model.Textures[diffuseTextureID]);
                    res.mainTexture = texture;
                }
            }
        }
        return(res);
    }
        public Material MergeMaterials(PbrMaterial vpxMaterial, Material texturedMaterial)
        {
            var nonTexturedMaterial = CreateMaterial(vpxMaterial, null);
            var mergedMaterial      = new Material(GetShader());

            mergedMaterial.CopyPropertiesFromMaterial(texturedMaterial);

            mergedMaterial.name = nonTexturedMaterial.name;
            mergedMaterial.SetColor(BaseColor, nonTexturedMaterial.GetColor(BaseColor));
            mergedMaterial.SetFloat(Metallic, nonTexturedMaterial.GetFloat(Metallic));
            mergedMaterial.SetFloat(Smoothness, nonTexturedMaterial.GetFloat(Smoothness));

            return(mergedMaterial);
        }
Example #44
0
    public Body(double m, float r, float x, float y, float z, string id, Color color = default(Color))
    {
        mass          = m;
        radius        = 10 * r;
        volume        = (4 / 3) * pi * (r * r * r);
        density       = mass / volume;
        xPos          = x;
        yPos          = y;
        zPos          = z;
        accelerationX = 0;
        accelerationY = 0;
        accelerationZ = 0;
        ID            = id;

        appearance = GameObject.CreatePrimitive(PrimitiveType.Sphere);
        appearance.transform.position   = new Vector3(xPos / 100, yPos / 100, zPos / 100);
        appearance.transform.localScale = new Vector3((10 * 2 * r) / 100, (10 * 2 * r) / 100, (10 * 2 * r) / 100);
        rigidBody = appearance.AddComponent <Rigidbody>();
        rigidBody.detectCollisions = false;

        trail      = appearance.AddComponent <TrailRenderer>();
        trail.time = 5;
        trail.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
        trail.receiveShadows    = false;
        trail.widthMultiplier   = 5;

        UnityEngine.Material mat = new UnityEngine.Material(Shader.Find("Standard"));
        if (color == default(Color))
        {
            color  = Color.gray;
            isStar = 0;
        }
        else
        {
            isStar = 1;
            mat.EnableKeyword("_EMISSION");
            mat.SetColor("_EmissionColor", new Color(255, 187, 0));
            //mat.EnableKeyword("_EMISSION");
            //mat.SetColor("_EmissionColor", new Color(255, 187, 0));
        }
        mat.color = color;
        appearance.GetComponent <Renderer>().material = mat;

        //Apply texture

        /*UnityEngine.Material mater = Earth;
         * mater.EnableKeyword("_EMISSION");
         * mater.SetColor("_EmissionColor", new Color(255, 187, 0));
         * appearance.GetComponent<Renderer>().material = mater;*/
    }
Example #45
0
        internal void SetBoardState(GameCell[] Field)
        {
            if (!_inited)
            {
                Debug.LogError($"View has not been inited!");
                return;
            }

            if (Field.Length != _changeableObjects.Count)
            {
                Debug.LogError($"Different dimensions!");
                return;
            }

            var cells   = new NativeArray <GameCell>(_changeableObjects.Count, Allocator.TempJob);
            var indexes = new NativeArray <int>(_changeableObjects.Count, Allocator.TempJob);
            var colors  = new NativeArray <Color>(_changeableObjects.Count, Allocator.TempJob);

            for (int i = 0; i < cells.Length; i++)
            {
                cells[i]   = Field[i];
                indexes[i] = i;
                colors[i]  = _changeableObjects[i].Color;
            }

            var job = new CellChanger()
            {
                Cells   = cells,
                Indexes = indexes,
                Colors  = colors,
            };

            var jobHandler = job.Schedule(_changeableObjects.Count, 10);

            jobHandler.Complete();

            for (int i = 0; i < _changeableObjects.Count; i++)
            {
                var renderMesh = _entityManager.GetSharedComponentData <RenderMesh>(_changeableObjects[i].Entity);
                var mat        = new UnityEngine.Material(renderMesh.material);
                mat.SetColor("_Color", colors[i]);
                renderMesh.material = mat;

                _entityManager.SetSharedComponentData(_changeableObjects[i].Entity, renderMesh);
            }

            cells.Dispose();
            colors.Dispose();
            indexes.Dispose();
        }
Example #46
0
        // マテリアルの登録
        private UnityEngine.Material EntryMaterial(int i)
        {
            UnityEngine.Material mat    = new UnityEngine.Material(Shader.Find("VertexLit"));
            Material             source = matList.materials[i];
            Texture tex = null;

            // テクスチャを貼る
            if (source.TextureFileName != "")
            {
                tex             = AssetDatabase.LoadAssetAtPath(folderPath + source.TextureFileName, typeof(Texture)) as Texture;
                mat.mainTexture = tex;
                mat.SetTextureScale("_MainTex", new Vector2(1, -1));
            }

            mat.color = source.DiffuseColor;
            mat.SetColor("_SpecColor", source.SpecularColor);
            mat.SetColor("_Emission", source.EmissionColor);
            mat.SetFloat("_Shiness", source.Specularity);
            mat.name = this.fileName + "_" + source.Name;

            AssetDatabase.CreateAsset(mat, folderPath + "Materials/" + mat.name + ".asset");
            return(mat);
        }
        public ResourceObject Parse(ByteBuffer bb)
        {
            Schema.Material _material = Schema.Material.GetRootAsMaterial(bb);

            ResourceObjectMaterial result = new ResourceObjectMaterial(_material.Shader);

            UnityEngine.Material material = result.Unity3dObject as UnityEngine.Material;
            material.name = _material.Name;

            for (int i = 0; i < _material.PropertiesLength; i++)
            {
                Schema.ShaderProperty p = _material.GetProperties(i);
                switch (p.Type)
                {
                case ShaderPropertyType.Float:
                case ShaderPropertyType.Range:
                {
                    Schema.ShaderPropertyFloat f = p.GetValue <Schema.ShaderPropertyFloat>(fObj);
                    material.SetFloat(p.Names, f.Value);
                }
                break;

                case ShaderPropertyType.Color:
                {
                    Schema.ShaderPropertyColor c = p.GetValue <Schema.ShaderPropertyColor>(cObj);
                    material.SetColor(p.Names, new UnityEngine.Color(c.Color.R, c.Color.G, c.Color.B, c.Color.A));
                }
                break;

                case ShaderPropertyType.Vector:
                {
                    Schema.ShaderPropertyVector v = p.GetValue <Schema.ShaderPropertyVector>(vObj);
                    material.SetVector(p.Names, new Vector4(v.Vector.X, v.Vector.Y, v.Vector.Z, v.Vector.W));
                }
                break;

                case ShaderPropertyType.TexEnv:
                {
                    Schema.ShaderPropertyTexture t = p.GetValue <Schema.ShaderPropertyTexture>(tObj);
                    material.SetTextureOffset(p.Names, new Vector2(t.Offset.X, t.Offset.Y));
                    material.SetTextureScale(p.Names, new Vector2(t.Scale.X, t.Scale.Y));
                    result.AddTexture(t.Name, p.Names);
                }
                break;
                }
            }

            return(result);
        }
Example #48
0
        public UnityEngine.Material CreateMaterial()
        {
            var material = new UnityEngine.Material(GetShader());
            var texture  = new Texture2D(512, 512, TextureFormat.RGBA32, true)
            {
                name = "BallDebugTexture"
            };

            texture.LoadImage(Resource.BallDebug.Data);
            material.SetTexture(BaseMap, texture);
            material.SetColor(BaseColor, Color.white);
            material.SetFloat(Metallic, 0.85f);
            material.SetFloat(Smoothness, 0.75f);
            return(material);
        }
        private UnityEngine.Material CreateMaterialFromXml(XElement xml)
        {
            // Does this material support alpha color key?
            string htmlColor       = ImportUtils.GetAttributeAsString(xml, "alphaColorKey", "");
            bool   usesDepthShader = ImportUtils.GetAttributeAsBoolean(xml, "usesDepthShaders", false);

            // Determine which shader we sould be using
            string shaderName = "Tiled2Unity/";

            // Are we using depth shaders?
            if (usesDepthShader)
            {
                shaderName += "Depth";
            }
            else
            {
                shaderName += "Default";
            }

            // Are we using color key shaders?
            Color?keyColor = null;

            if (!String.IsNullOrEmpty(htmlColor))
            {
                shaderName += " Color Key";

                // Sometimes Tiled saves out color without the leading # but we expect it to be there
                if (!htmlColor.StartsWith("#"))
                {
                    htmlColor = "#" + htmlColor;
                }

                byte r = byte.Parse(htmlColor.Substring(1, 2), System.Globalization.NumberStyles.HexNumber);
                byte g = byte.Parse(htmlColor.Substring(3, 2), System.Globalization.NumberStyles.HexNumber);
                byte b = byte.Parse(htmlColor.Substring(5, 2), System.Globalization.NumberStyles.HexNumber);
                keyColor = new Color32(r, g, b, 255);
            }

            UnityEngine.Material material = new UnityEngine.Material(UnityEngine.Shader.Find(shaderName));

            if (keyColor.HasValue)
            {
                material.SetColor("_AlphaColorKey", keyColor.Value);
            }

            return(material);
        }
Example #50
0
            public static void SetObjectEmissionColor(GameObject obj, Color col)
            {
                Renderer r = obj.GetComponent <Renderer>();

                if (r)
                {
                    UMaterial material = new UMaterial(r.sharedMaterial);
                    if (material.HasProperty("_EmissionColor"))
                    {
                        material.SetColor("_EmissionColor", col);
                        obj.GetComponent <Renderer>().sharedMaterial = material;
                    }
                    else
                    {
                        U.Object.Destroy(material);
                    }
                }
            }
        // This is a hack for GI. PVR looks in the shader for a texture named "_MainTex" to extract the opacity of the material for baking. In the same manner, "_Cutoff" and "_Color" are also necessary.
        // Since we don't have those parameters in our shaders we need to provide a "fake" useless version of them with the right values for the GI to work.
        private static void SetupMainTexForAlphaTestGI(UnityEngine.Material unityMaterial, string colorMapPropertyName, string colorPropertyName)
        {
            if (unityMaterial.HasProperty(colorMapPropertyName))
            {
                var mainTex = unityMaterial.GetTexture(colorMapPropertyName);
                unityMaterial.SetTexture(MainTex, mainTex);
            }

            if (unityMaterial.HasProperty(colorPropertyName))
            {
                var color = unityMaterial.GetColor(colorPropertyName);
                unityMaterial.SetColor(Color, color);
            }

            if (unityMaterial.HasProperty("_AlphaCutoff"))
            {
                var cutoff = unityMaterial.GetFloat(AlphaCutoff);
                unityMaterial.SetFloat(Cutoff, cutoff);
            }
        }
Example #52
0
 public void ChangeMaterial(string name, Color color = default(Color), float rate = 0)
 {
     AssetUtil.LoadAssetAsync(name,
                              (pathOrAddress, uObj, userData) =>
     {
         UnityEngine.Material cMaterial = uObj as UnityEngine.Material;
         cMaterial.SetColor("_Frenel", color);
         /// 变化范围1-0-1-0-1...
         cMaterial.SetFloat("_Fre", 1);
         cMaterial.SetFloat("_Vertex", 0);
         if (m_MeshRenderer)
         {
             m_MeshRenderer.material = cMaterial;
             if (rate > 0)
             {
                 m_Rate = rate;
             }
         }
     }
                              );
 }
Example #53
0
        private static void CreateSingleMat(Material mat)
        {
            string strRes = mat.uuid.Replace("/", "");

            UnityEngine.Color color = GetColour(mat);
            // Create a simple material asset
            var material = new UnityEngine.Material(Shader.Find("Standard"));

            material.SetColor("_Color", color);
            string path   = "Assets/Resources/" + strRes + ".mat";
            var    myType = AssetDatabase.LoadAssetAtPath(path, typeof(UnityEngine.Material)) as UnityEngine.Material;

            if (myType == null)
            {
                AssetDatabase.CreateAsset(material, path);
            }
            else
            {
                myType.SetColor("_Color", color);
            }
        }
Example #54
0
        protected virtual UnityEngine.Material CreateMaterial(Material def, bool useVertexColors)
        {
            if (def.ContentsWithVC == null || def.ContentsWithoutVC == null)
            {
                Shader shader;

                // get the shader to use for this material
                try
                {
                    if (def.PbrMetallicRoughness != null)
                    {
                        shader = _shaderCache[MaterialType.PbrMetallicRoughness];
                    }
                    else if (_root.ExtensionsUsed != null && _root.ExtensionsUsed.Contains("KHR_materials_common") &&
                             def.CommonConstant != null)
                    {
                        shader = _shaderCache[MaterialType.CommonConstant];
                    }
                    else
                    {
                        shader = _shaderCache[MaterialType.PbrMetallicRoughness];
                    }
                }
                catch (KeyNotFoundException e)
                {
                    Debug.LogWarningFormat("No shader supplied for type of glTF material {0}, using Standard fallback", def.Name);
                    shader = Shader.Find("Standard");
                }

                shader.maximumLOD = MaximumLod;

                var material = new UnityEngine.Material(shader);

                if (def.AlphaMode == AlphaMode.MASK)
                {
                    material.SetOverrideTag("RenderType", "TransparentCutout");
                    material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                    material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                    material.SetInt("_ZWrite", 1);
                    material.EnableKeyword("_ALPHATEST_ON");
                    material.DisableKeyword("_ALPHABLEND_ON");
                    material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                    material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest;
                    material.SetFloat("_Cutoff", (float)def.AlphaCutoff);
                }
                else if (def.AlphaMode == AlphaMode.BLEND)
                {
                    material.SetOverrideTag("RenderType", "Transparent");
                    material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
                    material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                    material.SetInt("_ZWrite", 0);
                    material.DisableKeyword("_ALPHATEST_ON");
                    material.EnableKeyword("_ALPHABLEND_ON");
                    material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                    material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
                }
                else
                {
                    material.SetOverrideTag("RenderType", "Opaque");
                    material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                    material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                    material.SetInt("_ZWrite", 1);
                    material.DisableKeyword("_ALPHATEST_ON");
                    material.DisableKeyword("_ALPHABLEND_ON");
                    material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                    material.renderQueue = -1;
                }

                if (def.DoubleSided)
                {
                    material.SetInt("_Cull", (int)CullMode.Off);
                }
                else
                {
                    material.SetInt("_Cull", (int)CullMode.Back);
                }

                if (def.PbrMetallicRoughness != null)
                {
                    var pbr = def.PbrMetallicRoughness;

                    material.SetColor("_Color", pbr.BaseColorFactor);

                    if (pbr.BaseColorTexture != null)
                    {
                        var texture = pbr.BaseColorTexture.Index.Value;
                        material.SetTexture("_MainTex", CreateTexture(texture));
                    }

                    material.SetFloat("_Metallic", (float)pbr.MetallicFactor);

                    if (pbr.MetallicRoughnessTexture != null)
                    {
                        var texture = pbr.MetallicRoughnessTexture.Index.Value;
                        material.SetTexture("_MetallicRoughnessMap", CreateTexture(texture));
                    }

                    material.SetFloat("_Roughness", (float)pbr.RoughnessFactor);
                }

                if (def.CommonConstant != null)
                {
                    material.SetColor("_AmbientFactor", def.CommonConstant.AmbientFactor);

                    if (def.CommonConstant.LightmapTexture != null)
                    {
                        material.EnableKeyword("LIGHTMAP_ON");

                        var texture = def.CommonConstant.LightmapTexture.Index.Value;
                        material.SetTexture("_LightMap", CreateTexture(texture));
                        material.SetInt("_LightUV", def.CommonConstant.LightmapTexture.TexCoord);
                    }

                    material.SetColor("_LightFactor", def.CommonConstant.LightmapFactor);
                }

                if (def.NormalTexture != null)
                {
                    var texture = def.NormalTexture.Index.Value;
                    material.SetTexture("_BumpMap", CreateTexture(texture));
                    material.SetFloat("_BumpScale", (float)def.NormalTexture.Scale);
                }

                if (def.OcclusionTexture != null)
                {
                    var texture = def.OcclusionTexture.Index;

                    material.SetFloat("_OcclusionStrength", (float)def.OcclusionTexture.Strength);

                    if (def.PbrMetallicRoughness != null &&
                        def.PbrMetallicRoughness.MetallicRoughnessTexture != null &&
                        def.PbrMetallicRoughness.MetallicRoughnessTexture.Index.Id == texture.Id)
                    {
                        material.EnableKeyword("OCC_METAL_ROUGH_ON");
                    }
                    else
                    {
                        material.SetTexture("_OcclusionMap", CreateTexture(texture.Value));
                    }
                }

                if (def.EmissiveTexture != null)
                {
                    var texture = def.EmissiveTexture.Index.Value;
                    material.EnableKeyword("EMISSION_MAP_ON");
                    material.SetTexture("_EmissionMap", CreateTexture(texture));
                    material.SetInt("_EmissionUV", def.EmissiveTexture.TexCoord);
                }

                material.SetColor("_EmissionColor", def.EmissiveFactor);

                def.ContentsWithoutVC = material;
                def.ContentsWithVC    = new UnityEngine.Material(material);
                def.ContentsWithVC.EnableKeyword("VERTEX_COLOR_ON");
            }

            return(def.GetContents(useVertexColors));
        }
        protected virtual MaterialCacheData CreateMaterial(GLTF.Schema.Material def, int materialIndex)
        {
            MaterialCacheData materialWrapper = null;

            if (materialIndex < 0 || _assetCache.MaterialCache[materialIndex] == null)
            {
                Shader shader;

                // get the shader to use for this material
                try
                {
                    if (_root.ExtensionsUsed != null && _root.ExtensionsUsed.Contains("KHR_materials_pbrSpecularGlossiness"))
                    {
                        shader = _shaderCache[MaterialType.KHR_materials_pbrSpecularGlossiness];
                    }
                    else if (def.PbrMetallicRoughness != null)
                    {
                        shader = _shaderCache[MaterialType.PbrMetallicRoughness];
                    }
                    else if (_root.ExtensionsUsed != null && _root.ExtensionsUsed.Contains("KHR_materials_common") &&
                             def.CommonConstant != null)
                    {
                        shader = _shaderCache[MaterialType.CommonConstant];
                    }
                    else
                    {
                        shader = _shaderCache[MaterialType.PbrMetallicRoughness];
                    }
                }
                catch (KeyNotFoundException)
                {
                    Debug.LogWarningFormat("No shader supplied for type of glTF material {0}, using Standard fallback", def.Name);
                    shader = Shader.Find("Standard");
                }

                shader.maximumLOD = MaximumLod;

                var material = new UnityEngine.Material(shader);

                if (def.AlphaMode == AlphaMode.MASK)
                {
                    material.SetOverrideTag("RenderType", "TransparentCutout");
                    material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                    material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                    material.SetInt("_ZWrite", 1);
                    material.EnableKeyword("_ALPHATEST_ON");
                    material.DisableKeyword("_ALPHABLEND_ON");
                    material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                    material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest;
                    material.SetFloat("_Cutoff", (float)def.AlphaCutoff);
                }
                else if (def.AlphaMode == AlphaMode.BLEND)
                {
                    material.SetOverrideTag("RenderType", "Transparent");
                    material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
                    material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                    material.SetInt("_ZWrite", 0);
                    material.DisableKeyword("_ALPHATEST_ON");
                    material.EnableKeyword("_ALPHABLEND_ON");
                    material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                    material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
                }
                else
                {
                    material.SetOverrideTag("RenderType", "Opaque");
                    material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                    material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                    material.SetInt("_ZWrite", 1);
                    material.DisableKeyword("_ALPHATEST_ON");
                    material.DisableKeyword("_ALPHABLEND_ON");
                    material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                    material.renderQueue = -1;
                }

                if (def.DoubleSided)
                {
                    material.SetInt("_Cull", (int)CullMode.Off);
                }
                else
                {
                    material.SetInt("_Cull", (int)CullMode.Back);
                }

                if (def.PbrMetallicRoughness != null)
                {
                    var pbr = def.PbrMetallicRoughness;

                    material.SetColor("_Color", pbr.BaseColorFactor.ToUnityColor());

                    if (pbr.BaseColorTexture != null)
                    {
                        var textureDef = pbr.BaseColorTexture.Index.Value;
                        material.SetTexture("_MainTex", CreateTexture(textureDef));

                        ApplyTextureTransform(pbr.BaseColorTexture, material, "_MainTex");
                    }

                    material.SetFloat("_Metallic", (float)pbr.MetallicFactor);

                    if (pbr.MetallicRoughnessTexture != null)
                    {
                        var texture = pbr.MetallicRoughnessTexture.Index.Value;
                        material.SetTexture("_MetallicRoughnessMap", CreateTexture(texture));

                        ApplyTextureTransform(pbr.MetallicRoughnessTexture, material, "_MetallicRoughnessMap");
                    }

                    material.SetFloat("_Roughness", (float)pbr.RoughnessFactor);
                }

                if (_root.ExtensionsUsed != null && _root.ExtensionsUsed.Contains(KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME))
                {
                    KHR_materials_pbrSpecularGlossinessExtension specGloss = def.Extensions[KHR_materials_pbrSpecularGlossinessExtensionFactory.EXTENSION_NAME] as KHR_materials_pbrSpecularGlossinessExtension;

                    if (specGloss.DiffuseTexture != null)
                    {
                        var texture = specGloss.DiffuseTexture.Index.Value;
                        material.SetTexture("_MainTex", CreateTexture(texture));

                        ApplyTextureTransform(specGloss.DiffuseTexture, material, "_MainTex");
                    }
                    else
                    {
                        material.SetColor("_Color", specGloss.DiffuseFactor.ToUnityColor());
                    }

                    if (specGloss.SpecularGlossinessTexture != null)
                    {
                        var texture = specGloss.SpecularGlossinessTexture.Index.Value;
                        material.SetTexture("_SpecGlossMap", CreateTexture(texture));
                        material.EnableKeyword("_SPECGLOSSMAP");

                        ApplyTextureTransform(specGloss.SpecularGlossinessTexture, material, "_SpecGlossMap");
                    }
                    else
                    {
                        material.SetVector("_SpecColor", specGloss.SpecularFactor.ToUnityVector3());
                        material.SetFloat("_Glossiness", (float)specGloss.GlossinessFactor);
                    }
                }

                if (def.CommonConstant != null)
                {
                    material.SetColor("_AmbientFactor", def.CommonConstant.AmbientFactor.ToUnityColor());

                    if (def.CommonConstant.LightmapTexture != null)
                    {
                        material.EnableKeyword("LIGHTMAP_ON");

                        var texture = def.CommonConstant.LightmapTexture.Index.Value;
                        material.SetTexture("_LightMap", CreateTexture(texture));
                        material.SetInt("_LightUV", def.CommonConstant.LightmapTexture.TexCoord);

                        ApplyTextureTransform(def.CommonConstant.LightmapTexture, material, "_LightMap");
                    }

                    material.SetColor("_LightFactor", def.CommonConstant.LightmapFactor.ToUnityColor());
                }

                if (def.NormalTexture != null)
                {
                    var texture = def.NormalTexture.Index.Value;
                    material.SetTexture("_BumpMap", CreateTexture(texture));
                    material.SetFloat("_BumpScale", (float)def.NormalTexture.Scale);
                    material.EnableKeyword("_NORMALMAP");

                    ApplyTextureTransform(def.NormalTexture, material, "_BumpMap");
                }

                if (def.OcclusionTexture != null)
                {
                    var texture = def.OcclusionTexture.Index;

                    material.SetFloat("_OcclusionStrength", (float)def.OcclusionTexture.Strength);

                    if (def.PbrMetallicRoughness != null &&
                        def.PbrMetallicRoughness.MetallicRoughnessTexture != null &&
                        def.PbrMetallicRoughness.MetallicRoughnessTexture.Index.Id == texture.Id)
                    {
                        material.EnableKeyword("OCC_METAL_ROUGH_ON");
                    }
                    else
                    {
                        material.SetTexture("_OcclusionMap", CreateTexture(texture.Value));

                        ApplyTextureTransform(def.OcclusionTexture, material, "_OcclusionMap");
                    }
                }

                if (def.EmissiveTexture != null)
                {
                    var texture = def.EmissiveTexture.Index.Value;
                    material.EnableKeyword("EMISSION_MAP_ON");
                    material.EnableKeyword("_EMISSION");
                    material.SetTexture("_EmissionMap", CreateTexture(texture));
                    material.SetInt("_EmissionUV", def.EmissiveTexture.TexCoord);

                    ApplyTextureTransform(def.EmissiveTexture, material, "_EmissionMap");
                }

                material.SetColor("_EmissionColor", def.EmissiveFactor.ToUnityColor());

                materialWrapper = new MaterialCacheData
                {
                    UnityMaterial = material,
                    UnityMaterialWithVertexColor = new UnityEngine.Material(material),
                    GLTFMaterial = def
                };

                materialWrapper.UnityMaterialWithVertexColor.EnableKeyword("VERTEX_COLOR_ON");

                if (materialIndex > 0)
                {
                    _assetCache.MaterialCache[materialIndex] = materialWrapper;
                }
            }

            return(materialIndex > 0 ? _assetCache.MaterialCache[materialIndex] : materialWrapper);
        }
        private void WriteUiforms <TValue>(EditorImporter importer, UnityEngine.Material material, SeinMaterialUniform <TValue>[] uniforms)
        {
            foreach (SeinMaterialUniform <TValue> uniform in uniforms)
            {
                var name = uniform.name;
                switch (uniform.type)
                {
                case (ESeinMaterialUniformType.FLOAT):
                    material.SetFloat(name, (uniform as SeinMaterialUniformFloat).value);
                    break;

                case (ESeinMaterialUniformType.INT):
                    material.SetInt(name, (uniform as SeinMaterialUniformInt).value);
                    break;

                case (ESeinMaterialUniformType.SAMPLER_2D):
                    var tex = importer.GetTexture((uniform as SeinMaterialUniformTexture).id.Id);
                    material.SetTexture(name, tex);
                    break;

                // todo: support cubemap
                case (ESeinMaterialUniformType.SAMPLER_CUBE):
                    break;

                case (ESeinMaterialUniformType.FLOAT_VEC2):
                    var fv2 = (uniform as SeinMaterialUniformFloatVec2).value;
                    material.SetFloatArray(name, new List <float> {
                        fv2.x, fv2.y
                    });
                    break;

                case (ESeinMaterialUniformType.FLOAT_VEC3):
                    var fv3 = (uniform as SeinMaterialUniformFloatVec3).value;
                    material.SetFloatArray(name, new List <float> {
                        fv3.x, fv3.y, fv3.z
                    });
                    break;

                case (ESeinMaterialUniformType.FLOAT_VEC4):
                    if (uniform.GetType() == typeof(SeinMaterialUniformColor))
                    {
                        material.SetColor(name, (uniform as SeinMaterialUniformColor).value);
                    }
                    material.SetVector(name, (uniform as SeinMaterialUniformFloatVec4).value);
                    break;

                case (ESeinMaterialUniformType.FLOAT_MAT2):
                    material.SetMatrix(name, (uniform as SeinMaterialUniformFloatMat2).value);
                    break;

                case (ESeinMaterialUniformType.FLOAT_MAT3):
                    material.SetMatrix(name, (uniform as SeinMaterialUniformFloatMat3).value);
                    break;

                case (ESeinMaterialUniformType.FLOAT_MAT4):
                    material.SetMatrix(name, (uniform as SeinMaterialUniformFloatMat4).value);
                    break;

                default:
                    break;
                }
            }
        }
        private UnityEngine.Material CreateMaterial(Material def, bool useVertexColors)
        {
            UnityEngine.Material material = new UnityEngine.Material(useVertexColors ? ColorMaterial : NoColorMaterial);

            material.shader.maximumLOD = MaximumLod;

            if (def.AlphaMode == AlphaMode.MASK)
            {
                material.SetOverrideTag("RenderType", "TransparentCutout");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                material.SetInt("_ZWrite", 1);
                material.EnableKeyword("_ALPHATEST_ON");
                material.DisableKeyword("_ALPHABLEND_ON");
                material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.AlphaTest;
                material.SetFloat("_Cutoff", (float)def.AlphaCutoff);
            }
            else if (def.AlphaMode == AlphaMode.BLEND)
            {
                material.SetOverrideTag("RenderType", "Transparent");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
                material.SetInt("_ZWrite", 0);
                material.DisableKeyword("_ALPHATEST_ON");
                material.EnableKeyword("_ALPHABLEND_ON");
                material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = (int)UnityEngine.Rendering.RenderQueue.Transparent;
            }
            else
            {
                material.SetOverrideTag("RenderType", "Opaque");
                material.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.One);
                material.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.Zero);
                material.SetInt("_ZWrite", 1);
                material.DisableKeyword("_ALPHATEST_ON");
                material.DisableKeyword("_ALPHABLEND_ON");
                material.DisableKeyword("_ALPHAPREMULTIPLY_ON");
                material.renderQueue = -1;
            }

            if (def.DoubleSided)
            {
                material.SetInt("_Cull", (int)CullMode.Off);
            }
            else
            {
                material.SetInt("_Cull", (int)CullMode.Back);
            }

            if (useVertexColors)
            {
                material.EnableKeyword("VERTEX_COLOR_ON");
            }

            if (def.PbrMetallicRoughness != null)
            {
                var pbr = def.PbrMetallicRoughness;

                material.SetColor("_Color", pbr.BaseColorFactor);

                if (pbr.BaseColorTexture != null)
                {
                    var texture = pbr.BaseColorTexture.Index.Value;
                    material.SetTexture("_MainTex", _imageCache[texture.Source.Value]);
                }

                material.SetFloat("_Metallic", (float)pbr.MetallicFactor);

                if (pbr.MetallicRoughnessTexture != null)
                {
                    var texture = pbr.MetallicRoughnessTexture.Index.Value;
                    material.SetTexture("_MetallicRoughnessMap", _imageCache[texture.Source.Value]);
                }

                material.SetFloat("_Roughness", (float)pbr.RoughnessFactor);
            }

            if (def.CommonConstant != null)
            {
                material.SetColor("_AmbientFactor", def.CommonConstant.AmbientFactor);

                if (def.CommonConstant.LightmapTexture != null)
                {
                    material.EnableKeyword("LIGHTMAP_ON");

                    var texture = def.CommonConstant.LightmapTexture.Index.Value;
                    material.SetTexture("_LightMap", _imageCache[texture.Source.Value]);
                    material.SetInt("_LightUV", def.CommonConstant.LightmapTexture.TexCoord);
                }

                material.SetColor("_LightFactor", def.CommonConstant.LightmapFactor);
            }

            if (def.NormalTexture != null)
            {
                var texture = def.NormalTexture.Index.Value;
                material.EnableKeyword("_NORMALMAP");
                material.SetTexture("_BumpMap", _imageCache[texture.Source.Value]);
                material.SetFloat("_BumpScale", (float)def.NormalTexture.Scale);
            }
            else
            {
                material.SetTexture("_BumpMap", null);
                material.DisableKeyword("_NORMALMAP");
            }

            if (def.OcclusionTexture != null)
            {
                var texture = def.OcclusionTexture.Index;

                material.SetFloat("_OcclusionStrength", (float)def.OcclusionTexture.Strength);

                if (def.PbrMetallicRoughness != null &&
                    def.PbrMetallicRoughness.MetallicRoughnessTexture.Index.Id == texture.Id)
                {
                    material.EnableKeyword("OCC_METAL_ROUGH_ON");
                }
                else
                {
                    material.SetTexture("_OcclusionMap", _imageCache[texture.Value.Source.Value]);
                }
            }

            if (def.EmissiveTexture != null)
            {
                var texture = def.EmissiveTexture.Index.Value;
                material.EnableKeyword("_EMISSION");
                material.EnableKeyword("EMISSION_MAP_ON");
                material.SetTexture("_EmissionMap", _imageCache[texture.Source.Value]);
                material.SetInt("_EmissionUV", def.EmissiveTexture.TexCoord);
            }

            material.SetColor("_EmissionColor", def.EmissiveFactor);

            return(material);
        }
Example #58
0
    void Update()
    {
        if (DoSetCloneState)
        {
            SetCloneState(CloneStateToSet);
            DoSetCloneState = false;
        }

        if (UpdateCloneAmount)
        {
            SetCloneAmount(CloneCount);
            UpdateCloneAmount = false;
        }
        if (DisableKinectUpdate)
        {
            UserMeshVisualizer.Instance.BlockKinectUpdate = true;
            UserMeshVisualizer.Instance.DisableMeshUpdate = true;
            DisableKinectUpdate = false;
        }
        else if (EnableKinectUpdate)
        {
            UserMeshVisualizer.Instance.BlockKinectUpdate = false;
            UserMeshVisualizer.Instance.DisableMeshUpdate = false;
            EnableKinectUpdate = false;
        }
        else if (DisableUserRender)
        {
            GameObject.Find("UserMesh").GetComponent <MeshRenderer>().enabled = false;
            DisableUserRender = false;
        }
        else if (EnableUserRender)
        {
            GameObject.Find("UserMesh").GetComponent <MeshRenderer>().enabled = true;
            // GameObject.Find("OutputQuad").GetComponent<MeshRenderer>().enabled = true;
            EnableUserRender = false;
        }
        else if (ActivateClones)
        {
            EnableKinectUpdate = true;
            EnableUserRender   = true;
            ParticleSceneController.Instance.OneFiveNineOut = true;
            MidiManager.Instance.ShowClones();
            if (GameObject.Find("LightPlane") != null)
            {
                GameObject.Find("LightPlane").SetActive(false);
            }
            var baseOutputQuad = GameObject.Find("OutputQuad");
            var effector       = baseOutputQuad.GetComponent <TrackerOutputEffector>();
            effector.RefreshEveryFrame = true;
            ActivateClones             = false;
        }
        else if (CycleCloneColours)
        {
            CycleColours();
        }

        if (ActivateRainOutroState)
        {
            var baseOutputQuad = GameObject.Find("OutputQuad");
            var effector       = baseOutputQuad.GetComponent <TrackerOutputEffector>();
            effector.CloneColourPosition = 3;
            effector.RefreshCloneColours();
            AirSticksNoteOnCyclesColours = false;
        }
        if (SillhouetteOff)
        {
            var baseOutputQuad = GameObject.Find("OutputQuad");
            var renderer       = baseOutputQuad.GetComponent <Renderer>();
            renderer.material.SetColor("_TintColor", new Color(0, 0, 0, 0));
            var effector = baseOutputQuad.GetComponent <TrackerOutputEffector>();
            effector.CloneDistance = 0.005f;
            ActivateRainOutroState = false;
            SillhouetteOff         = false;
        }

        if (ActivateCloneIntroState)
        {
            var baseOutputQuad = GameObject.Find("OutputQuad");
            var effector       = baseOutputQuad.GetComponent <TrackerOutputEffector>();
            effector.CloneColourPosition = 1;
            effector.RefreshCloneColours();
            AirSticksNoteOnCyclesColours = false;
            ActivateCloneIntroState      = false;
        }

        if (RemoveAllClones)
        {
            var baseOutputQuad = GameObject.Find("OutputQuad");
            var children       = baseOutputQuad.GetComponentsInChildren <Transform>();
            foreach (var child in children)
            {
                if (child.gameObject != baseOutputQuad)
                {
                    Destroy(child.gameObject);
                }
            }
            var effector = baseOutputQuad.GetComponent <TrackerOutputEffector>();
            effector.LeftHandClones.Clear();
            effector.RightHandClones.Clear();
            RemoveAllClones            = false;
            effector.RefreshEveryFrame = false;
        }

        if (FadeOutStart)
        {
            FadeOutStartTime = Time.time;
            FadingOut        = true;
            FadeOutMaterial  = OutputQuad.GetComponent <MeshRenderer>().material;
            FadeOutStart     = false;
        }
        if (FadingOut)
        {
            var position = (Time.time - FadeOutStartTime) / FadeOutLength;
            if (position >= 1)
            {
                position  = 1;
                FadingOut = false;
            }
            var v = 1 - position;
            FadeOutMaterial.SetColor("_TintColor", Color.HSVToRGB(0, 0, v));
        }
    }
        protected virtual void CreateUnityMaterial(GLTF.Schema.Material def, int materialIndex)
        {
            Extension specularGlossinessExtension = null;
            bool      isSpecularPBR = def.Extensions != null && def.Extensions.TryGetValue("KHR_materials_pbrSpecularGlossiness", out specularGlossinessExtension);

            Shader shader = isSpecularPBR ? Shader.Find("Standard (Specular setup)") : Shader.Find("Standard");

            var material = new UnityEngine.Material(shader);

            material.hideFlags = HideFlags.DontUnloadUnusedAsset;             // Avoid material to be deleted while being built
            material.name      = def.Name;

            //Transparency
            if (def.AlphaMode == AlphaMode.MASK)
            {
                GLTFUtils.SetupMaterialWithBlendMode(material, GLTFUtils.BlendMode.Cutout);
                material.SetFloat("_Mode", 1);
                material.SetFloat("_Cutoff", (float)def.AlphaCutoff);
            }
            else if (def.AlphaMode == AlphaMode.BLEND)
            {
                GLTFUtils.SetupMaterialWithBlendMode(material, GLTFUtils.BlendMode.Fade);
                material.SetFloat("_Mode", 3);
            }

            if (def.NormalTexture != null)
            {
                var       texture       = def.NormalTexture.Index.Id;
                Texture2D normalTexture = getTexture(texture) as Texture2D;

                //Automatically set it to normal map
                TextureImporter im = AssetImporter.GetAtPath(AssetDatabase.GetAssetPath(normalTexture)) as TextureImporter;
                im.textureType = TextureImporterType.NormalMap;
                im.SaveAndReimport();
                material.SetTexture("_BumpMap", getTexture(texture));
                material.SetFloat("_BumpScale", (float)def.NormalTexture.Scale);
            }

            if (def.EmissiveTexture != null)
            {
                material.EnableKeyword("EMISSION_MAP_ON");
                var texture = def.EmissiveTexture.Index.Id;
                material.SetTexture("_EmissionMap", getTexture(texture));
                material.SetInt("_EmissionUV", def.EmissiveTexture.TexCoord);
            }

            // PBR channels
            if (specularGlossinessExtension != null)
            {
                KHR_materials_pbrSpecularGlossinessExtension pbr = (KHR_materials_pbrSpecularGlossinessExtension)specularGlossinessExtension;
                material.SetColor("_Color", pbr.DiffuseFactor.ToUnityColor().gamma);
                if (pbr.DiffuseTexture != null)
                {
                    var texture = pbr.DiffuseTexture.Index.Id;
                    material.SetTexture("_MainTex", getTexture(texture));
                }

                if (pbr.SpecularGlossinessTexture != null)
                {
                    var texture = pbr.SpecularGlossinessTexture.Index.Id;
                    material.SetTexture("_SpecGlossMap", getTexture(texture));
                    material.SetFloat("_GlossMapScale", (float)pbr.GlossinessFactor);
                    material.SetFloat("_Glossiness", (float)pbr.GlossinessFactor);
                }
                else
                {
                    material.SetFloat("_Glossiness", (float)pbr.GlossinessFactor);
                }

                Vector3 specularVec3 = pbr.SpecularFactor.ToUnityVector3();
                material.SetColor("_SpecColor", new Color(specularVec3.x, specularVec3.y, specularVec3.z, 1.0f));

                if (def.OcclusionTexture != null)
                {
                    var texture = def.OcclusionTexture.Index.Id;
                    material.SetFloat("_OcclusionStrength", (float)def.OcclusionTexture.Strength);
                    material.SetTexture("_OcclusionMap", getTexture(texture));
                }

                GLTFUtils.SetMaterialKeywords(material, GLTFUtils.WorkflowMode.Specular);
            }
            else if (def.PbrMetallicRoughness != null)
            {
                var pbr = def.PbrMetallicRoughness;

                material.SetColor("_Color", pbr.BaseColorFactor.ToUnityColor().gamma);
                if (pbr.BaseColorTexture != null)
                {
                    var texture = pbr.BaseColorTexture.Index.Id;
                    material.SetTexture("_MainTex", getTexture(texture));
                }

                material.SetFloat("_Metallic", (float)pbr.MetallicFactor);
                material.SetFloat("_Glossiness", 1.0f - (float)pbr.RoughnessFactor);

                if (pbr.MetallicRoughnessTexture != null)
                {
                    var texture = pbr.MetallicRoughnessTexture.Index.Id;
                    UnityEngine.Texture2D inputTexture  = getTexture(texture) as Texture2D;
                    List <Texture2D>      splitTextures = splitMetalRoughTexture(inputTexture, def.OcclusionTexture != null, (float)pbr.MetallicFactor, (float)pbr.RoughnessFactor);
                    material.SetTexture("_MetallicGlossMap", splitTextures[0]);

                    if (def.OcclusionTexture != null)
                    {
                        material.SetFloat("_OcclusionStrength", (float)def.OcclusionTexture.Strength);
                        material.SetTexture("_OcclusionMap", splitTextures[1]);
                    }
                }

                GLTFUtils.SetMaterialKeywords(material, GLTFUtils.WorkflowMode.Metallic);
            }

            material.SetColor("_EmissionColor", def.EmissiveFactor.ToUnityColor().gamma);
            material = _assetManager.saveMaterial(material, materialIndex);
            _assetManager._parsedMaterials.Add(material);
            material.hideFlags = HideFlags.None;
        }
        public UnityEngine.Material CreateMaterial(PbrMaterial vpxMaterial, TableBehavior table, StringBuilder debug = null)
        {
            var unityMaterial = new UnityEngine.Material(GetShader())
            {
                name = vpxMaterial.Id
            };

            // apply some basic manipulations to the color. this just makes very
            // very white colors be clipped to 0.8204 aka 204/255 is 0.8
            // this is to give room to lighting values. so there is more modulation
            // of brighter colors when being lit without blow outs too soon.
            var col = vpxMaterial.Color.ToUnityColor();

            if (vpxMaterial.Color.IsGray() && col.grayscale > 0.8)
            {
                debug?.AppendLine("Color manipulation performed, brightness reduced.");
                col.r = col.g = col.b = 0.8f;
            }

            // alpha for color depending on blend mode
            ApplyBlendMode(unityMaterial, vpxMaterial.MapBlendMode);
            if (vpxMaterial.MapBlendMode == Engine.VPT.BlendMode.Translucent)
            {
                col.a = Mathf.Min(1, Mathf.Max(0, vpxMaterial.Opacity));
            }
            unityMaterial.SetColor(BaseColor, col);

            // validate IsMetal. if true, set the metallic value.
            // found VPX authors setting metallic as well as translucent at the
            // same time, which does not render correctly in unity so we have
            // to check if this value is true and also if opacity <= 1.
            if (vpxMaterial.IsMetal && (!vpxMaterial.IsOpacityActive || vpxMaterial.Opacity >= 1))
            {
                unityMaterial.SetFloat(Metallic, 1f);
                debug?.AppendLine("Metallic set to 1.");
            }

            // roughness / glossiness
            unityMaterial.SetFloat(Smoothness, vpxMaterial.Roughness);

            // map
            if (table != null && vpxMaterial.HasMap)
            {
                unityMaterial.SetTexture(BaseColorMap, table.GetTexture(vpxMaterial.Map.Name));
            }

            // normal map
            if (table != null && vpxMaterial.HasNormalMap)
            {
                unityMaterial.EnableKeyword("_NORMALMAP");
                unityMaterial.EnableKeyword("_NORMALMAP_TANGENT_SPACE");

                unityMaterial.SetInt(NormalMapSpace, 0);                 // 0 = TangentSpace, 1 = ObjectSpace
                unityMaterial.SetFloat(NormalScale, 0f);                 // TODO FIXME: setting the scale to 0 for now. anything above 0 makes the entire unity editor window become black which is more likely a unity bug

                unityMaterial.SetTexture(NormalMap, table.GetTexture(vpxMaterial.NormalMap.Name));
            }

            // GI hack. This is a necessary step, see respective code in BaseUnlitGUI.cs of the HDRP source
            SetupMainTexForAlphaTestGI(unityMaterial, "_BaseColorMap", "_BaseColor");

            return(unityMaterial);
        }