- Home /
Dynamic create Terrain and change the material by Script
I want to create Terrain by the script,and I used the terrainData to Create a terrain.Now I want to give the terrain a material.But I have some questions: when I write the code like: ter.renderer.material = mat;
the Unity will give this exception:
===================Exception
MissingComponentException: There is no 'Renderer' attached to the "Terrain" game object, but a script is trying to access it. You probably need to add a Renderer to the game object "Terrain". Or your script needs to check if the component is attached before using it.
=================
but when I add Renderer like this: ter.AddComponent("Renderer");
the Unity will give a Warning like this
=================Warning
Cannot add component of type 'Renderer' because it is abstract. Add component of type that is derived from 'Renderer' instead.
=================
So I search this problem on Google.Some person said that I should use the MeshRenderer instead.So I Write the code like : ter.AddComponent("MeshRenderer");
but it also doesn't work:
========================Warning
Can't add component 'MeshRenderer' to Terrain because such a component is already added to the game object!
========================
Now I do not know how to do, who can tell me. Thanks very much.I want to create the terrain dynamic and create the material dynamic by script.
Answer by _dns_ · Aug 18, 2014 at 03:40 PM
Hi,
Try setting the material with Terrain.materialTemplate. I can't see this in the documentation but it works on my project (in some Editor code, didn't try it at run-time)
Thanks,do you have some sample code?I can't find the Terrain.materialTemplate.Is that an API of terrain?
Thanks a lot,I have solved this problem by your way.I find the terrain.materialTemplate . At the beginning I create the Terrain by CreateTerrainGameObject, it returns a Gameobject, so I can not find this interface. Now I find it in a Terrain variable 。
Terrain t = ter.GetComponent<Terrain>();
if(t)
{
t.materialTemplate = mat;
}
Cool, glad it helped! (wasn't notified of your previous comment until now, sometimes notification lags a few days...)
Your answer
Follow this Question
Related Questions
Applying offset to a texture via script 1 Answer
ExportTerrain doesn't work 1 Answer
Procedurally generating terrain? 0 Answers
Terrain material breaking when adding holes 0 Answers
Modelling Terrain in Blender 1 Answer