Attribute









How do I use Attribute
Below are practical examples compiled from projects for learning and reference purposes

Featured Snippets


File name: Animals.cs Copy
14         public void Start()
15         {
16             string[] names = new string[] { "dog", "monkey", "pig", "fox", "giraffe", "panda", "rhino", "tiger", "elephant", "lion" };
17
18             animals = new List();
19             int animalIndex = 0;
20
21             UpgradeInfo upgradeInfo = new UpgradeInfo();
22
23             GameObject animalPlayer = (GameObject)Instantiate(Resources.Load("Animals/" + names[Attr.currentAnimal]));
24             animalPlayer.transform.parent = gameObject.transform;
25             animalPlayer.transform.localPosition = new Vector3(-3.5f + 0.7f * animalIndex, -0.9f, 0);
26             setSortingLayer(animalPlayer, "Animal8");
27             Animal player = animalPlayer.AddComponent();
28             player.setAnimalName(names[Attr.currentAnimal]);
29             player.animalIndex = animalIndex;
30             player.gameScreen = gameScreen;
31             float speedPlayer = upgradeInfo.getItem(Attr.currentAnimal, 0, false);
32             float jumpPlayer = upgradeInfo.getItem(Attr.currentAnimal, 1, false);
33             player.setAnimalProperties(speedPlayer, jumpPlayer);
34             animalPlayer.layer = LayerMask.NameToLayer("Animal1");
35
36             animals.Add(animalPlayer);
37             animalIndex++;
38
39             animalPlayer.GetComponent().Play("run");
40             //animalPlayer.GetComponent().SetBool(Animal.IS_PLAYER, true);
41
42             TextAsset xml = Resources.Load("Levels/WorldMap" + (Attr.currentWorld + 1));
43             XmlDocument xmlDoc = new XmlDocument();
44             xmlDoc.Load(new StringReader(xml.text));
45
46             XmlNodeList xmlNodeList = xmlDoc.DocumentElement.ChildNodes;
47             XmlNodeList levelNodeList = xmlNodeList.Item(Attr.currentLevel).ChildNodes;
48             for (int i = 0; i < levelNodeList.Count; i++)
49             {
50                 int numberAnimal = int.Parse(levelNodeList.Item(i).Attributes.Item(0).Value);
51                 string animalName = levelNodeList.Item(i).Attributes.Item(1).Value.ToLower();
52
53                 for (int k = 0; k < numberAnimal; k++)
54                 {
55                     GameObject animalObject = (GameObject)Instantiate(Resources.Load("Animals/" + animalName));
56                     animalObject.transform.parent = gameObject.transform;
57                     animalObject.transform.localPosition = new Vector3(-3.5f + 0.7f*animalIndex, -0.9f, 0);
58                     setSortingLayer(animalObject, "Animal" + animalIndex);
59                     Animal animal = animalObject.AddComponent();
60                     animal.setAnimalName(animalName.ToLower() + "_blue");
61                     animal.animalIndex = animalIndex;
62                     animal.gameScreen = gameScreen;
63                     float speed = upgradeInfo.getSpeed(i);
64                     float jump = upgradeInfo.getJump(i);
65                     animal.setAnimalProperties(speed, jump);
66                     animalObject.layer = LayerMask.NameToLayer("Animal" + (animalIndex + 1));
67                     animals.Add(animalObject);
68                     animalIndex++;
69
70                     animalObject.GetComponent().Play("run_blue");
71
72                     //animalObject.GetComponent().SetBool(Animal.IS_PLAYER, false);
73                 }
74             }
75         }
File name: BitmapFont.cs Copy
26     public BitmapFont(string pathPNG, string pathXML, GameObject gameObject)
27     {
28         this.gameObject = gameObject;
29         sprites = new Dictionary();
30         yoffsets_xadvances = new Dictionary();
31         rects = new Dictionary();
32
33         Texture2D texture = Resources.Load(pathPNG);
34         float height = texture.height;
35         TextAsset xml = Resources.Load(pathXML);
36
37         XmlDocument test = new XmlDocument();
38         test.Load(new StringReader(xml.text));
39
40         //test.LoadXml(new StringReader(xml.text).ReadToEnd());
41         //string[] keys = new string[] {"x","y","width","height","yoffset","xadvance","letter"};
42
43         foreach (XmlNode node in test.DocumentElement.ChildNodes)
44         {
45             XmlAttributeCollection collection = node.Attributes;
46             Rect rect = new Rect(float.Parse(collection.Item(0).Value), height - float.Parse(collection.Item(1).Value) - float.Parse(collection.Item(3).Value), float.Parse(collection.Item(2).Value), float.Parse(collection.Item(3).Value));
47             rects.Add(collection.Item(6).Value, rect);
48             sprites.Add(collection.Item(6).Value, Sprite.Create(texture, rect, Vector2.zero));
49             yoffsets_xadvances.Add(collection.Item(6).Value, new Vector2(float.Parse(collection.Item(4).Value), float.Parse(collection.Item(5).Value)));
50         }
51     }
File name: TimelineKey.cs Copy
91         void GetCurveParams(XmlElement element)
92         {
93             //Get curve parameters using a bit of XPath, order using LINQ
94             //XPath 1.0 doesn't support regex - should match all attributes with names matching "c[0-9]+"
95             var curveParams = element.SelectNodes("@*[starts-with(name(), 'c') and string(number(substring(name(),2))) != 'NaN']")
96                 .OfType()
97                 .OrderBy(attr => attr.Name);
98
99             //Cast the values to float and convert to an array
100             CurveParams = curveParams
101                 .Select(attr => float.Parse(attr.Value))
102                 .ToArray();
103         }
File name: XmlUtils.cs Copy
31         public static bool TryGetString(this XmlNode node, string key, out string value)
32         {
33             value = default(string);
34             var attr = node.Attributes[key];
35             bool parsed = false;
36             if (attr != null)
37             {
38                 parsed = true;
39                 value = attr.Value;
40             }
41
42             return parsed;
43         }
File name: XmlUtils.cs Copy
45         public static bool TryGetInt(this XmlNode node, string key, out int value)
46         {
47             value = default(int);
48             var attr = node.Attributes[key];
49             bool parsed = false;
50             if (attr != null)
51             {
52                 parsed = int.TryParse(attr.Value, System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out value);
53             }
54
55             return parsed;
56         }
File name: XmlUtils.cs Copy
58         public static bool TryGetFloat(this XmlNode node, string key, out float value)
59         {
60             value = default(float);
61             var attr = node.Attributes[key];
62             bool parsed = false;
63             if (attr != null)
64             {
65                 parsed = float.TryParse(attr.Value, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out value);
66             }
67
68             return parsed;
69         }
File name: XmlUtils.cs Copy
99         public static string GetString(this XmlNode node, string key, string defaultVal)
100         {
101             string value = defaultVal;
102             var attr = node.Attributes[key];
103             if (attr != null)
104             {
105                 value = attr.Value;
106             }
107             return value;
108         }
File name: ImportTiled2Unity.Material.cs Copy
19         public Material FixMaterialForMeshRenderer(string objName, Renderer renderer)
20         {
21             string xmlPath = ImportUtils.GetXmlPath(objName);
22
23             XDocument xml = XDocument.Load(xmlPath);
24
25             // The mesh to match
26             string meshName = renderer.name;
27
28             // The mesh name may be decorated by Unity
29             string pattern = @"_MeshPart[\d]$";
30             Regex regex = new Regex(pattern);
31             meshName = regex.Replace(meshName, "");
32
33             var assignMaterials = xml.Root.Elements("AssignMaterial");
34
35             // Find an assignment that matches the mesh renderer
36             XElement match = assignMaterials.FirstOrDefault(el => el.Attribute("mesh").Value == meshName);
37
38             if (match == null)
39             {
40                 // The names of our meshes in the AssignMaterials elements may be wrong
41                 // This happened before when Unity replaced whitespace with underscore in our named meshes
42                 // That case is handled now, but there may be others
43                 StringBuilder builder = new StringBuilder();
44                 builder.AppendFormat("Could not find mesh named '{0}' for material matching\n", renderer.name);
45                 string choices = String.Join("\n ", assignMaterials.Select(m => m.Attribute("mesh").Value).ToArray());
46                 builder.AppendFormat("Choices are:\n {0}", choices);
47
48                 Debug.LogError(builder.ToString());
49                 return null;
50             }
51
52             string materialName = match.Attribute("material").Value;
53             string materialPath = ImportUtils.GetMaterialPath(materialName);
54
55             // Assign the material
56             renderer.sharedMaterial = AssetDatabase.LoadAssetAtPath(materialPath, typeof(Material)) as Material;
57
58             // Set the sorting layer for the mesh
59             string sortingLayer = match.Attribute("sortingLayerName").Value;
60             if (!String.IsNullOrEmpty(sortingLayer) && !SortingLayerExposedEditor.GetSortingLayerNames().Contains(sortingLayer))
61             {
62                 Debug.LogError(string.Format("Sorting Layer \"{0}\" does not exist. Check your Project Settings -> Tags and Layers", sortingLayer));
63                 renderer.sortingLayerName = "Default";
64             }
65             else
66             {
67                 renderer.sortingLayerName = sortingLayer;
68             }
69
70             // Set the sorting order
71             renderer.sortingOrder = ImportUtils.GetAttributeAsInt(match, "sortingOrder");
72
73             // Do we have an alpha color key?
74             string htmlColor = ImportUtils.GetAttributeAsString(match, "alphaColorKey", "");
75             if (!String.IsNullOrEmpty(htmlColor))
76             {
77                 // Take for granted color is in the form '#RRGGBB'
78                 byte r = byte.Parse(htmlColor.Substring(1, 2), System.Globalization.NumberStyles.HexNumber);
79                 byte g = byte.Parse(htmlColor.Substring(3, 2), System.Globalization.NumberStyles.HexNumber);
80                 byte b = byte.Parse(htmlColor.Substring(5, 2), System.Globalization.NumberStyles.HexNumber);
81                 Color color = new Color32(r, g, b, 255);
82                 renderer.sharedMaterial.SetColor("_AlphaColorKey", color);
83             }
84
85             return renderer.sharedMaterial;
86         }
File name: ImportTiled2Unity.Mesh.cs Copy
27         private void CreatePrefab(XElement xmlPrefab, string objPath)
28         {
29             var customImporters = GetCustomImporterInstances();
30
31             // Part 1: Create the prefab
32             string prefabName = xmlPrefab.Attribute("name").Value;
33             float prefabScale = ImportUtils.GetAttributeAsFloat(xmlPrefab, "scale", 1.0f);
34             GameObject tempPrefab = new GameObject(prefabName);
35             HandleCustomProperties(tempPrefab, xmlPrefab, customImporters);
36
37             // Part 2: Build out the prefab
38             AddGameObjectsTo(tempPrefab, xmlPrefab, objPath, customImporters);
39
40             // Part 3: Allow for customization from other editor scripts to be made on the prefab
41             // (These are generally for game-specific needs)
42             CustomizePrefab(tempPrefab, customImporters);
43
44             // Part 3.5: Apply the scale only after all children have been added
45             tempPrefab.transform.localScale = new Vector3(prefabScale, prefabScale, prefabScale);
46
47             // Part 4: Save the prefab, keeping references intact.
48             string prefabPath = ImportUtils.GetPrefabPath(prefabName);
49             UnityEngine.Object finalPrefab = AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject));
50
51             if (finalPrefab == null)
52             {
53                 // The prefab needs to be created
54                 ImportUtils.ReadyToWrite(prefabPath);
55                 finalPrefab = PrefabUtility.CreateEmptyPrefab(prefabPath);
56             }
57
58             // Replace the prefab, keeping connections based on name.
59             PrefabUtility.ReplacePrefab(tempPrefab, finalPrefab, ReplacePrefabOptions.ReplaceNameBased);
60
61             // Destroy the instance from the current scene hiearchy.
62             UnityEngine.Object.DestroyImmediate(tempPrefab);
63         }
File name: ImportTiled2Unity.Mesh.cs Copy
65         private void AddGameObjectsTo(GameObject parent, XElement xml, string objPath, IList customImporters)
66         {
67             foreach (XElement goXml in xml.Elements("GameObject"))
68             {
69                 string name = ImportUtils.GetAttributeAsString(goXml, "name", "");
70                 string copyFrom = ImportUtils.GetAttributeAsString(goXml, "copy", "");
71
72                 GameObject child = null;
73                 if (!String.IsNullOrEmpty(copyFrom))
74                 {
75                     child = CreateCopyFromMeshObj(copyFrom, objPath);
76                     if (child == null)
77                     {
78                         // We're in trouble. Errors should already be in the log.
79                         return;
80                     }
81                 }
82                 else
83                 {
84                     child = new GameObject();
85                 }
86
87                 if (!String.IsNullOrEmpty(name))
88                 {
89                     child.name = name;
90                 }
91
92                 float x = ImportUtils.GetAttributeAsFloat(goXml, "x", 0);
93                 float y = ImportUtils.GetAttributeAsFloat(goXml, "y", 0);
94                 child.transform.position = new Vector3(x, y, 0);
95
96                 // Assign the child to the parent
97                 child.transform.parent = parent.transform;
98
99                 // Do we have any collision data
100                 AddCollidersTo(child, goXml);
101
102                 // Do we have any children of our own?
103                 AddGameObjectsTo(child, goXml, objPath, customImporters);
104
105                 // Does this game object have a tag?
106                 AssignTagTo(child, goXml);
107
108                 // Does this game object have a layer?
109                 AssignLayerTo(child, goXml);
110
111                 // Are there any custom properties?
112                 HandleCustomProperties(child, goXml, customImporters);
113             }
114         }

Download file with original file name:Attribute

Attribute 117 lượt xem

Gõ tìm kiếm nhanh...