- Home /
How to Apply a Texture Over Another Texture in unity at runtime in unity
I wanted to replace the part of texture with another texture using raycast hit ?
Answer by MarshCZA · Mar 04, 2020 at 02:45 PM
Raycast Hit can be used to get the targeted pixel coordinate of your texture, you could then set up a grid centred around that pixel which is the size of your new texture (in pixels) and set the old texture's pixels to be the pixels of your new texture. The code here is a good starting point: https://docs.unity3d.com/ScriptReference/RaycastHit-textureCoord.html To use that code you would then need to look at nearby pixels on the old texture and update their colours by referencing the pixels in your new texture.
Firt Of All Thank You For Your Help :). I get Want I Needed but i wanted to Increase The Size Of the Brush. This Is $$anonymous$$y Code. But In This Code The Size of the Brush is Too Small. How I Can Increase The Size Of The Brush.
public Camera cam; public Texture2D mappingTexture;
void Start()
{
cam = GetComponent<Camera>();
}
void Update()
{
if (!Input.Get$$anonymous$$ouseButton(0))
return;
RaycastHit hit;
if (!Physics.Raycast(cam.ScreenPointToRay(Input.mousePosition), out hit))
return;
Renderer rend = hit.transform.GetComponent<Renderer>();
$$anonymous$$eshCollider meshCollider = hit.collider as $$anonymous$$eshCollider;
if (rend == null || rend.shared$$anonymous$$aterial == null || rend.shared$$anonymous$$aterial.mainTexture == null || meshCollider == null)
return;
// Getting The Coordinates of the $$anonymous$$ain Texture.
Texture2D tex = rend.material.mainTexture as Texture2D;
Vector2 pixelUV = hit.textureCoord;
pixelUV.x *= tex.width;
pixelUV.y *= tex.height;
// Getting The Colour Of new Texture.
Color color = mappingTexture.GetPixel((int)pixelUV.x, (int)pixelUV.y);
Debug.Log(color);
// Setting The Colour Of the Texture
tex.SetPixel((int)pixelUV.x, (int)pixelUV.y, color);
tex.Apply();
}