本文整理汇总了C#中UnityEngine.GameObject.SetParent方法的典型用法代码示例。如果您正苦于以下问题:C# GameObject.SetParent方法的具体用法?C# GameObject.SetParent怎么用?C# GameObject.SetParent使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类UnityEngine.GameObject
的用法示例。
在下文中一共展示了GameObject.SetParent方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateStar
private GameObject CreateStar(Vector2f position, float scale, ColorF color)
{
var star = new GameObject("Star");
star.SetParent(this.GameObject);
star.SetPosition2D(position);
star.SetScale2D(scale);
SpriteRenderer spriteRenderer = star.AddComponent<SpriteRenderer>();
spriteRenderer.sprite = this.Sprite;
spriteRenderer.color = color;
spriteRenderer.sortingOrder = -10000;
return star;
}
示例2: UpdateGraph
public void UpdateGraph( Font displayFont, params BarGraphElement[] graphElements ) {
if ( Values.Length > graphElements.Length ) {
Debug.LogWarningFormat(
"#{0}# There are more values than there are graphElements. Not all values will be added to the graph.",
typeof( BarGraphElement ).Name );
}
foreach ( RectTransform child in GraphSegments ) {
Destroy( child.gameObject );
}
for ( int n = 0; n < graphElements.Length && n < Values.Length; ++n ) {
RectTransform child =
new GameObject( graphElements[n].name,
typeof( RectTransform ),
typeof( CanvasRenderer ),
typeof( Image ),
typeof( LayoutElement ) ).GetComponent<RectTransform>();
if ( displayFont != null ) {
Text textDisplay =
new GameObject( "TextDisplay", typeof( RectTransform ), typeof( CanvasRenderer ), typeof( Text ) )
.GetComponent<Text>();
textDisplay.text = graphElements[n].Name;
textDisplay.rectTransform.anchorMin = Vector2.zero;
textDisplay.rectTransform.anchorMax = Vector2.one;
textDisplay.alignment = TextAnchor.MiddleCenter;
textDisplay.font = displayFont;
textDisplay.resizeTextForBestFit = true;
textDisplay.rectTransform.SetParent( child, false );
textDisplay.rectTransform.offsetMax = Vector2.zero;
textDisplay.rectTransform.offsetMin = Vector2.zero;
}
Image childImage = child.GetComponent<Image>();
childImage.color = graphElements[n].Color;
LayoutElement childLayout = child.GetComponent<LayoutElement>();
childLayout.flexibleHeight = Values[n];
child.SetParent( RectTransform, false );
}
}
示例3: generateMapAndPlayer
//.........这里部分代码省略.........
instantiateAndAdd(cliffTiles[8 + Random.Range(0, 2)], columns + 1, y, holders[(int)(holderID.CLIFF)]);
}
else if (y == eastGate - 1)
{
instantiateAndAdd(cliffTiles[14], columns, y, holders[(int)(holderID.CLIFF)]);
instantiateAndAdd(cliffTiles[Random.Range(0, 2)], columns + 1, y, holders[(int)(holderID.CLIFF)]);
}
else if (Mathf.Abs(y - (eastGate + 1)) >= 3)
{
instantiateAndAdd(cliffTiles[12 + Random.Range(0, 2)], columns, y, holders[(int)(holderID.CLIFF)]);
rockTilePositions.Add(new Vector3(columns + 1, y, 0));
}
}
// random generation of rock tiles
foreach (Vector3 pos in rockTilePositions)
{
instantiateAndAdd(
rockFloorTiles[Random.Range(0, rockFloorTiles.Length)],
Mathf.FloorToInt(pos.x),
Mathf.FloorToInt(pos.y),
holders[(int)(holderID.CLIFF)]
);
}
// box colliders for the borders
for (int x = 0; x < columns; x++)
{
for (int y = 0; y < rows; y++)
{
if (arrayMap[x + (rows - 1 - y) * columns] == "#")
{
Transform border = new GameObject("collider").transform;
border.SetParent(holders[(int)(holderID.BOARD_COLLIDER)]);
border.Translate(x, y, 0);
border.gameObject.layer = LayerMask.NameToLayer("Object");
border.gameObject.AddComponent<BoxCollider2D>();
}
}
}
if (northGate >= 1 && northGate < columns - 1)
{
for (int x = northGate-1; x <= northGate+1; x += 2)
{
Transform border = new GameObject("collider").transform;
border.SetParent(holders[(int)(holderID.BOARD_COLLIDER)]);
border.Translate(x, rows + 1f, 0);
border.localScale += new Vector3(0, 2.0f, 0);
border.gameObject.layer = LayerMask.NameToLayer("Object");
border.gameObject.AddComponent<BoxCollider2D>();
}
}
if (southGate >= 1 && southGate < columns - 1)
{
for (int x = southGate - 1; x <= southGate + 1; x += 2)
{
Transform border = new GameObject("collider").transform;
border.SetParent(holders[(int)(holderID.BOARD_COLLIDER)]);
border.Translate(x, -2f, 0);
border.localScale += new Vector3(0, 2.0f, 0);
border.gameObject.layer = LayerMask.NameToLayer("Object");
border.gameObject.AddComponent<BoxCollider2D>();
}
示例4: GenerateBuildingsOnRoad
/// <summary>
/// Generate Buildings on the edges of the road
/// </summary>
private void GenerateBuildingsOnRoad(Road road)
{
//create building parent if none exists
if (_buildingParent == null)
{
_buildingParent = new GameObject("Buildings");
_buildingParent.SetParent(_townParent);
}
var cell = road.ParentCell;
int offset = _terrainSettings.RoadWidth;
const float minDistance = 0.2f;
//access building prefabs for this cell
var prefabs = GetPrefabsForType(cell.DistrictType);
if (prefabs == null)
{
return;
}
//Create an offset line of this road towards the inside of the cell
var offsetLine = road.GenerateOffsetParallelTowardsPoint(offset, cell.SitePoint);
//calculate total length of the line
var length = offsetLine.Length();
var traveled = minDistance * 2;
//keep repeating until the end is reached
while (traveled < length - (minDistance * 2))
{
//get point on line using normalized values [0,1]
var pc = traveled / length;
var pos = offsetLine.FindRandomPointOnLine(pc, pc);
//Select a random prefab
var prefab = prefabs.GetRandomValue();
//Create a building site from this point
var bs = BuildingSite.FromPoint(pos);
bs.ParentRoad = road;
//Spawn the building
SpawnBuilding(pos.ToVector3(), prefab, bs);
//travel along the line using the width of the building site
traveled += (minDistance + bs.Width / 2);
}
}
示例5: TryBuild
private void TryBuild(Entity entity, GameObject prefab, GameObject instance, string directory, string prefabPath, IDictionary<int, IDictionary<int, Sprite>> folders, ScmlObject scmlObject)
{
var controllerPath = string.Format ("{0}/{1}.controller", directory, entity.name);
var animator = instance.GetComponent<Animator> (); //Fetches the prefab's Animator
if (animator == null) animator = instance.AddComponent<Animator> (); //Or creates one if it doesn't exist
AnimatorController controller = null;
if (animator.runtimeAnimatorController != null) { //The controller we use is hopefully the controller attached to the animator
controller = animator.runtimeAnimatorController as AnimatorController ?? //Or the one that's referenced by an OverrideController
(AnimatorController)((AnimatorOverrideController)animator.runtimeAnimatorController).runtimeAnimatorController;
}
if (controller == null) { //Otherwise we have to check the AssetDatabase for our controller
controller = (AnimatorController)AssetDatabase.LoadAssetAtPath (controllerPath, typeof(AnimatorController));
if (controller == null) {
controller = AnimatorController.CreateAnimatorControllerAtPath (controllerPath); //Or create a new one if it doesn't exist.
ProcessingInfo.NewControllers.Add (controller);
}
animator.runtimeAnimatorController = controller;
}
var transforms = new Dictionary<string, Transform> (); //All of the bones and sprites, identified by TimeLine.name, because those are truly unique
transforms ["rootTransform"] = instance.transform; //The root GameObject needs to be part of this hierarchy as well
var defaultBones = new Dictionary<string, SpatialInfo> (); //These are basically the object states on the first frame of the first animation
var defaultSprites = new Dictionary<string, SpriteInfo> (); //They are used as control values in determining whether something has changed
var animBuilder = new AnimationBuilder (ProcessingInfo, folders, transforms, defaultBones, defaultSprites, prefabPath, controller);
var firstAnim = true; //The prefab's graphic will be determined by the first frame of the first animation
foreach (var animation in entity.animations) {
var timeLines = new Dictionary<int, TimeLine> ();
foreach (var timeLine in animation.timelines) //TimeLines hold all the critical data such as positioning and graphics used
timeLines [timeLine.id] = timeLine;
foreach (var key in animation.mainlineKeys) {
var parents = new Dictionary<int, string> (); //Parents are referenced by different IDs V_V
parents [-1] = "rootTransform"; //This is where "-1 == no parent" comes in handy
var boneRefs = new Queue<Ref> (key.boneRefs ?? new Ref[0]);
while (boneRefs.Count > 0) {
var bone = boneRefs.Dequeue ();
var timeLine = timeLines [bone.timeline];
parents [bone.id] = timeLine.name;
if (!transforms.ContainsKey (timeLine.name)) { //We only need to go through this once, so ignore it if it's already in the dict
if (parents.ContainsKey (bone.parent)) { //If the parent cannot be found, it will probably be found later, so save it
var parentID = parents [bone.parent];
var parent = transforms [parentID];
var child = parent.Find (timeLine.name); //Try to find the child transform if it exists
if (child == null) { //Or create a new one
child = new GameObject (timeLine.name).transform;
child.SetParent (parent);
}
transforms [timeLine.name] = child;
var spatialInfo = defaultBones [timeLine.name] = ArrayUtility.Find (timeLine.keys, x => x.id == bone.key).info;
if (!spatialInfo.processed) {
SpatialInfo parentInfo;
defaultBones.TryGetValue (parentID, out parentInfo);
spatialInfo.Process (parentInfo);
}
child.localPosition = new Vector3(spatialInfo.x, spatialInfo.y, 0f);
child.localRotation = spatialInfo.rotation;
child.localScale = new Vector3 (spatialInfo.scale_x, spatialInfo.scale_y, 1f);
}
else boneRefs.Enqueue (bone);
}
}
foreach (var oref in key.objectRefs) {
var timeLine = timeLines [oref.timeline];
if (!transforms.ContainsKey (timeLine.name)) { //Same as above
var parentID = parents [oref.parent];
var parent = transforms [parentID];
var child = parent.Find (timeLine.name);
if (child == null) {
child = new GameObject (timeLine.name).transform;
child.SetParent (parent);
}
transforms [timeLine.name] = child;
var swapper = child.GetComponent<TextureController> (); //Destroy the Sprite Swapper, we'll make a new one later
if (swapper != null) DestroyImmediate (swapper);
var renderer = child.GetComponent<SpriteRenderer> (); //Get or create a Sprite Renderer
if (renderer == null) renderer = child.gameObject.AddComponent<SpriteRenderer> ();
var spriteInfo = defaultSprites [timeLine.name] = (SpriteInfo)ArrayUtility.Find (timeLine.keys, x => x.id == 0).info;
renderer.sprite = folders [spriteInfo.folder] [spriteInfo.file];
if (!spriteInfo.processed) {
SpatialInfo parentInfo;
defaultBones.TryGetValue (parentID, out parentInfo);
spriteInfo.Process (parentInfo);
}
var spriteSize = scmlObject.GetSpriteSize(spriteInfo.folder, spriteInfo.file);
child.localEulerAngles = new Vector3 (0f, 0f, spriteInfo.angle);
child.localPosition = spriteInfo.PrefabPosition(spriteSize, spriteInfo.angle, oref.z_index); //Z-index helps determine draw order
//The reason I don't use layers or layer orders is because
child.localScale = new Vector3 (spriteInfo.scale_x, spriteInfo.scale_y, 1f); //There tend to be a LOT of body parts, it's better to treat
var color = renderer.color; //The entity as a single sprite for layer sorting purposes.
color.a = spriteInfo.a;
renderer.color = color;
if (!firstAnim) child.gameObject.SetActive (false); //Disable the GameObject if this isn't the first frame of the first animation
}
}
if (firstAnim) firstAnim = false;
}
try {
animBuilder.Build (animation, timeLines); //Builds the currently processed AnimationClip, see AnimationBuilder for more info
}
catch (Exception e) {
//.........这里部分代码省略.........
示例6: InitNameText
private void InitNameText()
{
var textTransform = _healthBar.FindChild("Name");
if (textTransform == null)
{
textTransform = new GameObject("Name", typeof(Text)).transform;
var rectTransform = textTransform.GetComponent<RectTransform>();
rectTransform.anchorMin = new Vector2(0, 1);
rectTransform.anchorMax = new Vector2(1, 1);
rectTransform.sizeDelta = new Vector2(0, 16);
rectTransform.pivot = new Vector2(.5f, 0);
textTransform.SetParent(_healthBar, false);
var text = textTransform.GetComponent<Text>();
text.text = "Name";
text.alignment = TextAnchor.MiddleCenter;
text.gameObject.SetActive(ShowName);
text.color = NameColor;
text.font = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
text.fontStyle = FontStyle.Bold;
text.supportRichText = false;
_nameText = text;
}
else
{
_nameText = textTransform.GetComponent<Text>();
}
}
示例7: InitLevelText
private void InitLevelText()
{
var tfm = _healthBar.FindChild("Level Bg");
if (tfm == null)
{
tfm = new GameObject("Level Bg", typeof (Image)).transform;
var rectTfm = tfm.GetComponent<RectTransform>();
rectTfm.anchorMin = new Vector2(0, .5f);
rectTfm.anchorMax = new Vector2(0, .5f);
rectTfm.sizeDelta = new Vector2(25, 25);
rectTfm.pivot = new Vector2(1, .5f);
tfm.SetParent(_healthBar, false);
var image = tfm.GetComponent<Image>();
image.sprite = Resources.Load<Sprite>("ENPCHealthBar-levelbg");
image.color = Color.black;
image.gameObject.SetActive(ShowLevel);
_levelBg = image;
}
else
{
_levelBg = tfm.GetComponent<Image>();
}
tfm = _healthBar.FindChild("Level");
if (tfm == null)
{
tfm = new GameObject("Level", typeof(Text)).transform;
var rectTfm = tfm.GetComponent<RectTransform>();
rectTfm.anchorMin = new Vector2(0, .5f);
rectTfm.anchorMax = new Vector2(0, .5f);
rectTfm.sizeDelta = new Vector2(25, 25);
rectTfm.pivot = new Vector2(1, .5f);
tfm.SetParent(_healthBar, false);
var levelText = tfm.GetComponent<Text>();
levelText.text = "1";
levelText.alignment = TextAnchor.MiddleCenter;
levelText.color = LevelColor;
levelText.font = Resources.GetBuiltinResource(typeof(Font), "Arial.ttf") as Font;
levelText.fontStyle = FontStyle.Bold;
levelText.supportRichText = false;
levelText.gameObject.SetActive(ShowLevel);
_levelText = levelText;
}
else
{
_levelText = tfm.GetComponent<Text>();
}
}
示例8: Start
/// <summary>
/// Start everything up and get it configured.
/// </summary>
public void Start()
{
try
{
rpmComp = RasterPropMonitorComputer.Instantiate(internalProp, true);
Transform textObjTransform = internalProp.FindModelTransform(transformName);
Vector3 localScale = internalProp.transform.localScale;
Transform offsetTransform = new GameObject().transform;
offsetTransform.gameObject.name = "JSILabel-" + this.internalProp.propID + "-" + this.GetHashCode().ToString();
offsetTransform.gameObject.layer = textObjTransform.gameObject.layer;
offsetTransform.SetParent(textObjTransform, false);
offsetTransform.Translate(transformOffset.x * localScale.x, transformOffset.y * localScale.y, 0.0f);
textObj = offsetTransform.gameObject.AddComponent<JSITextMesh>();
font = JUtil.LoadFont(fontName, fontQuality);
textObj.font = font;
//textObj.fontSize = fontQuality; // This doesn't work with Unity-embedded fonts
textObj.fontSize = font.fontSize;
if (!string.IsNullOrEmpty(anchor))
{
if (anchor == TextAnchor.LowerCenter.ToString())
{
textObj.anchor = TextAnchor.LowerCenter;
}
else if (anchor == TextAnchor.LowerLeft.ToString())
{
textObj.anchor = TextAnchor.LowerLeft;
}
else if (anchor == TextAnchor.LowerRight.ToString())
{
textObj.anchor = TextAnchor.LowerRight;
}
else if (anchor == TextAnchor.MiddleCenter.ToString())
{
textObj.anchor = TextAnchor.MiddleCenter;
}
else if (anchor == TextAnchor.MiddleLeft.ToString())
{
textObj.anchor = TextAnchor.MiddleLeft;
}
else if (anchor == TextAnchor.MiddleRight.ToString())
{
textObj.anchor = TextAnchor.MiddleRight;
}
else if (anchor == TextAnchor.UpperCenter.ToString())
{
textObj.anchor = TextAnchor.UpperCenter;
}
else if (anchor == TextAnchor.UpperLeft.ToString())
{
textObj.anchor = TextAnchor.UpperLeft;
}
else if (anchor == TextAnchor.UpperRight.ToString())
{
textObj.anchor = TextAnchor.UpperRight;
}
else
{
JUtil.LogErrorMessage(this, "Unrecognized anchor '{0}' in config for {1} ({2})", anchor, internalProp.propID, internalProp.propName);
}
}
if (!string.IsNullOrEmpty(alignment))
{
if (alignment == TextAlignment.Center.ToString())
{
textObj.alignment = TextAlignment.Center;
}
else if (alignment == TextAlignment.Left.ToString())
{
textObj.alignment = TextAlignment.Left;
}
else if (alignment == TextAlignment.Right.ToString())
{
textObj.alignment = TextAlignment.Right;
}
else
{
JUtil.LogErrorMessage(this, "Unrecognized alignment '{0}' in config for {1} ({2})", alignment, internalProp.propID, internalProp.propName);
}
}
float sizeScalar = 32.0f / (float)font.fontSize;
textObj.characterSize = fontSize * 0.00005f * sizeScalar;
textObj.lineSpacing = textObj.lineSpacing * lineSpacing;
// "Normal" mode
if (string.IsNullOrEmpty(switchTransform))
{
// Force oneshot if there's no variables:
oneshot |= !labelText.Contains("$&$");
string sourceString = labelText.UnMangleConfigText();
//.........这里部分代码省略.........
示例9: ToggleShowTerrain
public void ToggleShowTerrain(MapCellFlag flag, bool show)
{
Transform root;
if (show)
{
int markIndex;
if (!terrainRoots.TryGetValue(flag, out root))
{
root = new GameObject("Terrain_" + Enum.GetName(typeof(MapCellFlag), flag)).transform;
root.SetParent(terrainRoot, false);
terrainRoots.Add(flag, root);
List<int> indices = terrainMaskIndices.Values.ToList();
for (markIndex = 0; ; ++markIndex)
{
if (indices.IndexOf(markIndex) < 0)
break;
}
terrainMaskIndices[flag] = markIndex;
}
else
{
markIndex = terrainMaskIndices[flag];
}
root.localPosition = new Vector3(0, 0, markIndex * -0.1f);
float scale = Mathf.Max(0.2f, 1 - markIndex * 0.2f);
Color color = TerrainFlagInfo.GetColorByFlag(flag);
List<MapCell> cells = GetCellsByFlag(flag);
int cellCount = cells.Count;
int childCount = root.childCount;
for (int i = 0; i < cellCount; ++i)
{
MapCell cell = cells[i];
Transform terrainMark;
if (i >= childCount)
{
GameObject terrainMarkObj = Loader.LoadPrefab("Map/TerrainMark").Instantiate();
terrainMarkObj.GetComponent<SpriteRenderer>().color = color;
terrainMark = terrainMarkObj.transform;
terrainMark.SetParent(root, false);
}
else
{
terrainMark = root.GetChild(i);
}
terrainMark.position = cell.Position;
terrainMark.Translate(0, 0, -terrainMark.localPosition.z);
terrainMark.localScale = new Vector3(scale, scale);
}
for (int i = cellCount; i < childCount; ++i)
Destroy(root.GetChild(i).gameObject);
}
else
{
if (terrainRoots.TryGetValue(flag, out root))
{
Destroy(root.gameObject);
terrainRoots.Remove(flag);
terrainMaskIndices.Remove(flag);
}
}
}
示例10: SpawnProp
/// <summary>
/// Spawn a random prop on the terrain
/// </summary>
private void SpawnProp(Vector3 position)
{
//create a parent to keep the hiearchy clean
if (_propParent == null)
{
_propParent = new GameObject("Props");
_propParent.SetParent(_townParent);
}
//select a random prop
var prefab = _terrainSettings.Props.GetRandomValue();
//Get the height of the terrain at the spawn position
position.y = _terrain.SampleHeight(position);
if (isOverlapping(prefab, position))
{
return;
}
//instantiate the prefab
var prop = (GameObject)GameObject.Instantiate(prefab, position, Quaternion.identity);
prop.SetParent(_propParent);
//remove detail around the prop
RemoveDetailsAroundGameObject(prop);
//Add the prop for manual deleting
_spawnedProps.Add(prop);
}
示例11: Init
internal void Init(ResourceLoader loader)
{
MapRoot = gameObject.transform;
CellRoot = new GameObject("CellRoot").transform;
CellRoot.SetParent(MapRoot, false);
PathRoot = new GameObject("PathRoot").transform;
PathRoot.SetParent(MapRoot, false);
Loader = loader;
Cells = new Dictionary<int, MapCell>();
PathColors = new List<Color>();
PathObjectRoots = new List<GameObject>();
Paths = new List<MapPath>();
}
示例12: InitSlider
private void InitSlider()
{
var sliderTransform = _healthBar.FindChild("Slider");
if (sliderTransform == null)
{
sliderTransform = new GameObject("Slider", typeof(Slider)).transform;
RectTransformFillParent(sliderTransform.GetComponent<RectTransform>());
sliderTransform.SetParent(_healthBar, false);
var slider = sliderTransform.GetComponent<Slider>();
slider.interactable = false;
slider.maxValue = MaxValue;
slider.value = Value;
slider.transition = Selectable.Transition.None;
_slider = slider;
}
else
{
_slider = sliderTransform.GetComponent<Slider>();
}
//Background
var fillArea = sliderTransform.FindChild("Fill Area");
if (fillArea == null)
{
fillArea = new GameObject("Fill Area", typeof(RectTransform), typeof(Image)).transform;
RectTransformFillParent(fillArea.GetComponent<RectTransform>());
fillArea.SetParent(sliderTransform, false);
var backImage = fillArea.GetComponent<Image>();
backImage.sprite = Resources.Load<Sprite>("ENPCHealthBar");
backImage.type = Image.Type.Sliced;
backImage.color = BarBackgroundColor;
_backImage = backImage;
}
else
{
_backImage = fillArea.GetComponent<Image>();
}
//Foreground
var fill = fillArea.FindChild("Fill");
if (fill == null)
{
fill = new GameObject("Fill", typeof(RectTransform), typeof(Image)).transform;
var fillTransform = fill.GetComponent<RectTransform>();
RectTransformFillParent(fillTransform);
fill.SetParent(fillArea, false);
var frontImage = fill.GetComponent<Image>();
frontImage.sprite = _backImage.sprite;
frontImage.type = Image.Type.Sliced;
frontImage.color = BarColor;
_frontImage = frontImage;
_slider.fillRect = fillTransform;
}
else
{
_frontImage = fill.GetComponent<Image>();
}
}
示例13: InitValueText
private void InitValueText()
{
var valueTextTransform = _healthBar.FindChild("Value");
if (valueTextTransform == null)
{
valueTextTransform = new GameObject("Value", typeof(Text)).transform;
RectTransformFillParent(valueTextTransform.GetComponent<RectTransform>());
valueTextTransform.GetComponent<RectTransform>().offsetMax = new Vector2(-5,0);
valueTextTransform.SetParent(_healthBar, false);
var valueText = valueTextTransform.GetComponent<Text>();
valueText.text = MaxValue.ToString(CultureInfo.InvariantCulture);
valueText.alignment = TextAnchor.MiddleRight;
valueText.gameObject.SetActive(ShowValue);
valueText.color = ValueColor;
valueText.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
valueText.fontStyle = FontStyle.Bold;
valueText.supportRichText = false;
_valueText = valueText;
}
else
{
_valueText = valueTextTransform.GetComponent<Text>();
}
}
示例14: Initialize
private void Initialize(VehicleDef def, int[] colors = null)
{
Definition = def;
if (colors != null && colors[0] != -1) {
SetColors(colors);
} else {
var defaultClrs = CarColors.GetCarDefaults(Definition.ModelName);
if (defaultClrs != null) {
SetColors(defaultClrs[UnityEngine.Random.Range(0, defaultClrs.Count)]);
} else {
Debug.LogWarningFormat("No colours defined for {0}!", def.GameName);
}
}
name = Definition.GameName;
_geometryParts = Geometry.Load(Definition.ModelName,
TextureDictionary.Load(Definition.TextureDictionaryName),
TextureDictionary.Load("vehicle"),
TextureDictionary.Load("misc"));
_frames = _geometryParts.AttachFrames(transform, MaterialFlags.Vehicle);
var wheelFrame = _frames.FirstOrDefault(x => x.Name == "wheel");
if (wheelFrame == null) {
Debug.LogWarningFormat("No wheels defined for {0}!", def.GameName);
Destroy(gameObject);
return;
}
foreach (var frame in _frames) {
if (!frame.Name.StartsWith("wheel_")) continue;
if (!frame.Name.EndsWith("_dummy")) continue;
var childFrames = _frames.Where(x => x.ParentIndex == frame.Index);
// disable all children of wheel dummies
foreach (var childFrame in childFrames) {
childFrame.gameObject.SetActive(false);
}
var wheelAlignment = GetWheelAlignment(frame.Name);
Wheel inst;
// see if this wheel dummy has a wheel child
var wheel = childFrames.FirstOrDefault(x => x.Name == "wheel");
if (wheel == null) {
var copy = Instantiate(wheelFrame.transform);
copy.SetParent(frame.transform, false);
_wheels.Add(inst = new Wheel {
Alignment = wheelAlignment,
Parent = frame.transform,
Child = copy,
});
} else {
// all children of wheel dummies get set to inactive so activate this one
wheel.gameObject.SetActive(true);
_wheels.Add(inst = new Wheel {
Alignment = wheelAlignment,
Parent = frame.transform,
Child = wheel.transform,
});
}
if (inst.IsLeftHand) {
frame.transform.Rotate(Vector3.up, 180.0f);
}
inst.Complement = _wheels.FirstOrDefault(x =>
(x.Alignment & WheelAlignment.LeftRightMask) != (inst.Alignment & WheelAlignment.LeftRightMask) &&
(x.Alignment & WheelAlignment.FrontMidRearMask) == (inst.Alignment & WheelAlignment.FrontMidRearMask));
if (inst.Complement != null) {
inst.Complement.Complement = inst;
}
}
InitializePhysics();
foreach (var pair in _frames.Where(x => x.Name.StartsWith("door_"))) {
var doorAlignment = GetDoorAlignment(pair.Name);
if (doorAlignment == DoorAlignment.None) continue;
var hinge = pair.gameObject.AddComponent<HingeJoint>();
hinge.axis = Vector3.up;
hinge.useLimits = true;
var limit = 90.0f * ((doorAlignment == DoorAlignment.LeftFront || doorAlignment == DoorAlignment.LeftRear) ? 1.0f : -1.0f);
hinge.limits = new JointLimits { min = Mathf.Min(0, limit), max = Mathf.Max(0, limit), };
hinge.connectedBody = gameObject.GetComponent<Rigidbody>();
}
//.........这里部分代码省略.........
示例15: Bake
/// <summary>
/// Executes the baking.
/// </summary>
public void Bake(string trunkMeshPath, string foliageMeshPath)
{
//Get the root transform for the baked mesh.
//If one tree is selected, use it.
//Otherwise, just use the average position of all the selected trees.
Matrix4x4 rootM;
Vector3 avgPos = Vector3.zero;
if (selectedBranches.Length > 1)
{
avgPos = selectedBranches[0].transform.position;
for (int i = 1; i < selectedBranches.Length; ++i)
avgPos += selectedBranches[i].transform.position;
avgPos /= (float)selectedBranches.Length;
rootM = Matrix4x4.TRS(-avgPos, Quaternion.identity, Vector3.one);
}
else
{
rootM = selectedBranches[0].transform.worldToLocalMatrix;
}
IEnumerable<TreeCurve> curves = selectedBranches.SelectMany(go => go.GetComponentsInChildren<TreeCurve>());
//Create one big mesh for all the branches.
Mesh msh = CreateMesh(curves.Select(tc => tc.GetComponent<MeshFilter>()), rootM);
ExportOBJ(msh, trunkMeshPath, "Trunk");
msh.Clear();
//Create one big mesh for all the foliage.
CurveFoliage[] cFs = curves.GetComponentsInChildren<TreeCurve, CurveFoliage>().RemoveDuplicates().ToArray();
if (cFs.Length > 0)
{
if (cFs.Any(cf => cf.Mode == CurveFoliage.MeshModes.Point))
{
Debug.LogError("Can't currently output point foliage meshes to OBJ");
cFs = new CurveFoliage[0];
}
else
{
msh = CreateMesh(cFs.Select(cf => cf.GetComponent<MeshFilter>()), rootM);
ExportOBJ(msh, foliageMeshPath, "Foliage");
msh.Clear();
}
}
//Replace the current tree object with one that just has the baked assets.
//Put the original objects inside the new one and deactivate it.
Transform bakedObj = new GameObject("Baked Trees").transform;
if (selectedBranches.Length > 1)
{
bakedObj.position = avgPos;
bakedObj.rotation = Quaternion.identity;
bakedObj.localScale = Vector3.one;
}
else
{
Transform oldObj = selectedBranches[0].transform;
bakedObj.position = oldObj.position;
bakedObj.rotation = oldObj.rotation;
bakedObj.localScale = oldObj.localScale;
}
AssetDatabase.Refresh();
Transform trunkChild = new GameObject("Trunk").transform;
trunkChild.SetParent(bakedObj, false);
MeshFilter mf = trunkChild.gameObject.AddComponent<MeshFilter>();
mf.sharedMesh = AssetDatabase.LoadAssetAtPath<Mesh>(PathUtils.GetRelativePath(trunkMeshPath,
"Assets"));
MeshRenderer mr = trunkChild.gameObject.AddComponent<MeshRenderer>();
mr.sharedMaterial = branchMat;
if (cFs.Length > 0)
{
Transform foliageChild = new GameObject("Foliage").transform;
foliageChild.SetParent(bakedObj, false);
mf = foliageChild.gameObject.AddComponent<MeshFilter>();
mf.sharedMesh = AssetDatabase.LoadAssetAtPath<Mesh>(PathUtils.GetRelativePath(foliageMeshPath,
"Assets"));
mr = foliageChild.gameObject.AddComponent<MeshRenderer>();
mr.sharedMaterial = foliageMat;
}
}