【问题标题】:Random selection from a List and assign fields to variables从列表中随机选择并将字段分配给变量
【发布时间】:2015-07-22 03:22:47
【问题描述】:

我一直在网上寻找一个直截了当的答案,我尝试过的所有示例都对我不起作用。我需要从 List 中随机选择一个元素,然后将其中两个字段分配给两个单独的 Text 组件,然后将第三个字符串分配给我将用于修改文件名的变量(对于动物类型的屏幕截图)在我的列表中)。这是我到目前为止所拥有的,但我的随机部分错了,我收到错误“错误 CS0119:表达式表示 type', where avariable',value' ormethod group' 是预期的”。我该如何解决?

AnimalDescription.cs

public string name;
public string description;
public string screenshotPrefix;

// Constructor to allocate string values
public AnimalDescription(string newName, string newDescription, string newScreenshotPrefix)
{
    name = newName;
    description = newDescription;
    screenshotPrefix = newScreenshotPrefix;
}

GameSetup.cs

void Start()
{
    List<AnimalDescription> animalDescriptions = new List<AnimalDescription>();

    animalDescriptions.Add(new AnimalDescription(
        // animal name
        "Of the Bear-Ape ARCTOPITHECUS.",
        // animal description
        "There is in America a very deformed beast which the inhabitants call Haut or Hauti, and the Frenchmen, Guenon, " +
        "as big as a great African Munkey. His belly hangeth very low, his head and face like unto a childs, as may be seen by " +
        "this lively picture, and being taken it will fight like a young child. His skin is of an ash-colour, and hairy like a Bear; " +
        "he hath but three claws on a foot, as long as four fingers, and like the thornes of Privet, where-by he climeth up into the " +
        "highest trees, and for the most part liveth of the leaves of a certain tree being of an exceeding height, which the Americans " +
        "call Amahut, and thereof this beast is called Haut. Their tail is about three fingers long, having very little hair there-on; " +
        "I observed, that although it often rained, yet was that beast never wet.",
        // screenshot prefix
        "ARCTOPITHECUS_"
        ));
    animalDescriptions.Add(new AnimalDescription(
        // animal name
        "Of the SIMIVULPA, or Apifb-Fox.",
        // animal description
        "…they have seen a four-footed beast, the forepart like a Fox, and in the hinder part like an Ape, except that it had a mans " +
        "feet, and ears like a Bat, and underneath the common belly, there was a skin like a bag or scrip, where-in she keepeth, lodgeth, " +
        "and carryeth her young ones, until they are able to provide for themselves, without the help of their dam; neither do they come " +
        "forth of that receptacle, except it be to suck milk, or sport themselves, so that the same under-belly is her best remedy against " +
        "the furious Hunters, and other ravening beasts, to preserve her young ones, for she is incredibly swift, running with that carriage " +
        "as if she has no burden. It hath a tail like a Munkey…",
        // screenshot prefix
        "SIMIVULPA_"
        ));
    animalDescriptions.Add(new AnimalDescription(
        // animal name
        "The SCYTHIAN WOLF.",
        // animal description
        "…they have seen a four-footed beast, the forepart like a Fox, and in the hinder part like an Ape, except that it had a mans " +
        "feet, and ears like a Bat, and underneath the common belly, there was a skin like a bag or scrip, where-in she keepeth, lodgeth, " +
        "and carryeth her young ones, until they are able to provide for themselves, without the help of their dam; neither do they come " +
        "forth of that receptacle, except it be to suck milk, or sport themselves, so that the same under-belly is her best remedy against " +
        "the furious Hunters, and other ravening beasts, to preserve her young ones, for she is incredibly swift, running with that carriage " +
        "as if she has no burden. It hath a tail like a Munkey…",
        // screenshot prefix
        "SCYTHIAN_WOLF_"
        ));
    animalDescriptions.Add(new AnimalDescription(
        // animal name
        "Of the TATUS, or Guinean Beast.",
        // animal description
        "This is a four-footed strange Beast, it is naturally covered with a hard shell, divided and interlined like the fins of fishes, " +
        "outwardly seeming buckled to the back like Coat-armor, within which the beast draweth up his body, as a Hedge-hog doth within his " +
        "prickled skin; and therefore I take it to be a Brasilian Hedge-hog. It is not much greater than a little Pig, and by the snout, ears, " +
        "legs, and feet thereof, it seemeth to be of that kind, saving that the snout is a little broader, and shorter than a Pigs, and the " +
        "tail very long like a Lizards or Rats, and one of these being brought into France, did live upon the eating of seeds, and fruits of " +
        "the Gardens, but it appeareth by that picture, or rather the stuffed, which Adriausus Mercellus the Apothecary…that the feet thereof " +
        "are not cloven into two parts like Swine, but rather into many like Dogs, for upon the hinderfeet there are five toes, and upon the " +
        "fore feet four, whereof two are so small that they are scarce visible. The breadth of that same skin was about seven fingers, and the " +
        "length of it two spans, the shell or crust upon the back of it did not reach down unto the rump or tail, but broke off as it were upon " +
        "the hips, some four fingers from the tail.",
        // screenshot prefix
        "TATUS_"
        ));
    animalDescriptions.Add(new AnimalDescription(
        // animal name
        "Of the GULON",
        // animal description
        "This Beast was not known by the Ancients, but hath been since discovered in the Northern parts of the World, and because of the " +
        "voracity thereof, it is called  (Gula)…is thought to be engendered by a Hyena and a Lioness, for the quality it resembleth a Hiena, " +
        "and it is the same which is called (Crocuta;) it is a devouring and an unprofitable creature, having sharper teeth than other creatures. " +
        "Some think it is derived of a Wolf and a Dog, for it is about the bigness of a Dog; it hath the face of Cat, the body and tail of a Fox; " +
        "being black of colour; his feet and nails be most sharp, his skin rusty, the hair very sharp, and it feedeth upon dead carkases. When it " +
        "hath found a dead carcass he eateth thereof so violently, that his belly standeth out like a bell; then he seeketh for some narrow passage " +
        "betwixt two trees, and there draweth through his body, by pressing whereof, he driveth out the meat which he had eaten; and being so emptied " +
        "returneth and devoureth as much as he did before, and goeth again and emptieth himself as in former manner; and so continueth eating and " +
        "emptying till all be eaten.",
        // screenshot prefix
        "GULON_"
        ));
    animalDescriptions.Add(new AnimalDescription(
        // animal name
        "Of the SUCCORATH",
        // animal description
        "…it is of a very deformed shape, and monstrous presence, a great ravener and untamable wilde Beast. When the Hunters that desire her " +
        "skin set upon her, she flyeth very swift, carrying her young ones upon her back, and covering them with her broad tail: Hunters dig " +
        "several pits or great holes in the earth, which they cover with boughs, sticks, and earth, so weakly that if the Beast chance at any " +
        "time to come upon it, she and her young ones fall down into the pit and are taken. This cruel, untamable, impatient, violent, ravening, " +
        "and bloudy beast, perceiving that her natural strength cannot deliver her from the wit and policy of men her hunters, (for being inclosed " +
        "she can never get out again.)…she destroyeth them all with her own teeth; for there was never any of them taken alive…And this is all I " +
        "finde recorded of this most savage Beast.",
        // screenshot prefix
        "SUCCORATH_"
        ));

    RandomizeAnimals();
}

void RandomizeAnimals()
{
    System.Random rand = new System.Random();
    AnimalDescription myElement = AnimalDescription[rand.Next(AnimalDescription.Count)];

}

【问题讨论】:

  • 所以你找到了System.Random - 你有没有尝试过以任何方式使用它?
  • 在下面的链接中已经有类似的东西了......也许可以帮助你使用随机的东西......检查这个stackoverflow.com/questions/16333861/…

标签: c# list random unity3d


【解决方案1】:

如果你想在 xml 中保存启动数据,试试这个

​using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            AnimalDescriptions animalDescriptions = new AnimalDescriptions();
            animalDescriptions.Start();
            animalDescriptions.Serialize(FILENAME);
            AnimalDescriptions newAnimalDescriptions = animalDescriptions.DeSerialize(FILENAME);

        }
    }
    [XmlRoot("animalDescriptions")]
    public class AnimalDescriptions
    {
        [XmlElement("animalDescription")]
        public List<AnimalDescription> animalDescriptions { get; set; }

        public void Start()
        {
            animalDescriptions = new List<AnimalDescription>() {
                new AnimalDescription() {
                    name = "Of the Bear-Ape ARCTOPITHECUS.",
                    description = "There is in America a very deformed beast which the inhabitants call Haut or Hauti, and the Frenchmen, Guenon, " +
                    "as big as a great African Munkey. His belly hangeth very low, his head and face like unto a childs, as may be seen by " +
                    "this lively picture, and being taken it will fight like a young child. His skin is of an ash-colour, and hairy like a Bear; " +
                    "he hath but three claws on a foot, as long as four fingers, and like the thornes of Privet, where-by he climeth up into the " +
                    "highest trees, and for the most part liveth of the leaves of a certain tree being of an exceeding height, which the Americans " +
                    "call Amahut, and thereof this beast is called Haut. Their tail is about three fingers long, having very little hair there-on; " +
                    "I observed, that although it often rained, yet was that beast never wet.",
                    screenshotPrefix = "ARCTOPITHECUS_"
                },
                new AnimalDescription() {
                    name = "Of the SIMIVULPA, or Apifb-Fox.",
                    description = "…they have seen a four-footed beast, the forepart like a Fox, and in the hinder part like an Ape, except that it had a mans " +
                    "feet, and ears like a Bat, and underneath the common belly, there was a skin like a bag or scrip, where-in she keepeth, lodgeth, " +
                    "and carryeth her young ones, until they are able to provide for themselves, without the help of their dam; neither do they come " +
                    "forth of that receptacle, except it be to suck milk, or sport themselves, so that the same under-belly is her best remedy against " +
                    "the furious Hunters, and other ravening beasts, to preserve her young ones, for she is incredibly swift, running with that carriage " +
                    "as if she has no burden. It hath a tail like a Munkey…",
                    screenshotPrefix = "SIMIVULPA_"
                },
                new AnimalDescription() {
                    name = "The SCYTHIAN WOLF.",
                    description = "…they have seen a four-footed beast, the forepart like a Fox, and in the hinder part like an Ape, except that it had a mans " +
                    "feet, and ears like a Bat, and underneath the common belly, there was a skin like a bag or scrip, where-in she keepeth, lodgeth, " +
                    "and carryeth her young ones, until they are able to provide for themselves, without the help of their dam; neither do they come " +
                    "forth of that receptacle, except it be to suck milk, or sport themselves, so that the same under-belly is her best remedy against " +
                    "the furious Hunters, and other ravening beasts, to preserve her young ones, for she is incredibly swift, running with that carriage " +
                    "as if she has no burden. It hath a tail like a Munkey…",
                    screenshotPrefix = "SCYTHIAN_WOLF_"
                },
                new AnimalDescription() {
                    name = "Of the TATUS, or Guinean Beast.",
                    description = "This is a four-footed strange Beast, it is naturally covered with a hard shell, divided and interlined like the fins of fishes, " +
                    "outwardly seeming buckled to the back like Coat-armor, within which the beast draweth up his body, as a Hedge-hog doth within his " +
                    "prickled skin; and therefore I take it to be a Brasilian Hedge-hog. It is not much greater than a little Pig, and by the snout, ears, " +
                    "legs, and feet thereof, it seemeth to be of that kind, saving that the snout is a little broader, and shorter than a Pigs, and the " +
                    "tail very long like a Lizards or Rats, and one of these being brought into France, did live upon the eating of seeds, and fruits of " +
                    "the Gardens, but it appeareth by that picture, or rather the stuffed, which Adriausus Mercellus the Apothecary…that the feet thereof " +
                    "are not cloven into two parts like Swine, but rather into many like Dogs, for upon the hinderfeet there are five toes, and upon the " +
                    "fore feet four, whereof two are so small that they are scarce visible. The breadth of that same skin was about seven fingers, and the " +
                    "length of it two spans, the shell or crust upon the back of it did not reach down unto the rump or tail, but broke off as it were upon " +
                    "the hips, some four fingers from the tail.",
                    screenshotPrefix = "TATUS_"
                },
                new AnimalDescription() {
                    name = "Of the GULON",
                    description = "This Beast was not known by the Ancients, but hath been since discovered in the Northern parts of the World, and because of the " +
                    "voracity thereof, it is called  (Gula)…is thought to be engendered by a Hyena and a Lioness, for the quality it resembleth a Hiena, " +
                    "and it is the same which is called (Crocuta;) it is a devouring and an unprofitable creature, having sharper teeth than other creatures. " +
                    "Some think it is derived of a Wolf and a Dog, for it is about the bigness of a Dog; it hath the face of Cat, the body and tail of a Fox; " +
                    "being black of colour; his feet and nails be most sharp, his skin rusty, the hair very sharp, and it feedeth upon dead carkases. When it " +
                    "hath found a dead carcass he eateth thereof so violently, that his belly standeth out like a bell; then he seeketh for some narrow passage " +
                    "betwixt two trees, and there draweth through his body, by pressing whereof, he driveth out the meat which he had eaten; and being so emptied " +
                    "returneth and devoureth as much as he did before, and goeth again and emptieth himself as in former manner; and so continueth eating and " +
                    "emptying till all be eaten.",
                    screenshotPrefix = "GULON_"
                },
                new AnimalDescription() {
                    name = "Of the SUCCORATH",
                    description = "…it is of a very deformed shape, and monstrous presence, a great ravener and untamable wilde Beast. When the Hunters that desire her " +
                    "skin set upon her, she flyeth very swift, carrying her young ones upon her back, and covering them with her broad tail: Hunters dig " +
                    "several pits or great holes in the earth, which they cover with boughs, sticks, and earth, so weakly that if the Beast chance at any " +
                    "time to come upon it, she and her young ones fall down into the pit and are taken. This cruel, untamable, impatient, violent, ravening, " +
                    "and bloudy beast, perceiving that her natural strength cannot deliver her from the wit and policy of men her hunters, (for being inclosed " +
                    "she can never get out again.)…she destroyeth them all with her own teeth; for there was never any of them taken alive…And this is all I " +
                    "finde recorded of this most savage Beast.",
                    screenshotPrefix = "SUCCORATH_"
                }
            };

            RandomizeAnimals();
        }
        public void Serialize(string filename)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(AnimalDescriptions));

            StreamWriter writer = new StreamWriter(filename);
            serializer.Serialize(writer, this);
            writer.Flush();
            writer.Close();
            writer.Dispose();
        }
        public AnimalDescriptions DeSerialize(string filename)
        {
            XmlSerializer xs = new XmlSerializer(typeof(AnimalDescriptions));
            XmlTextReader reader = new XmlTextReader(filename);
            AnimalDescriptions animalDescriptions = (AnimalDescriptions)xs.Deserialize(reader);
            animalDescriptions.RandomizeAnimals();
            return animalDescriptions;
        }

        void RandomizeAnimals()
        {
            System.Random rand = new System.Random();
            foreach (AnimalDescription animalDescription in animalDescriptions)
            {
                animalDescription.randomNumber = rand.Next();
            }

            animalDescriptions.Sort((firstObj, secondObj) =>
            {
                return firstObj.randomNumber.CompareTo(secondObj.randomNumber);
            });

            //or
            //animalDescriptions = animalDescriptions.OrderBy(x => x.randomNumber).ToList();

        }

    }
    [XmlRoot("animalDescription")]
    public class AnimalDescription
    {
        [XmlAttribute("name")]
        public string name { get; set; }
        [XmlAttribute("description")]
        public string description { get; set; }
        [XmlAttribute("screenshotPrefix")]
        public string screenshotPrefix { get; set; }
        [XmlIgnore]
        public int randomNumber;

    }
}

【讨论】:

    【解决方案2】:

    我会为此添加评论,但我没有声望,所以我修改了代码(由 jdweng)在这里。

    using UnityEngine;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication1
    {
        class Program  : MonoBehaviour
        {
            static void Main(string[] args)
            {
                AnimalDescription animalDescription = new AnimalDescription();
                animalDescription.Start();
            }
        }
        public class AnimalDescription
        {
            public string name;
            public string description;
            public string screenshotPrefix;
            private int randomNumber;
            List<AnimalDescription> animalDescriptions = new List<AnimalDescription>();
    
            public AnimalDescription()
            {
            }
            // Constructor to allocate string values
            public AnimalDescription(string newName, string newDescription, string newScreenshotPrefix)
            {
                name = newName;
                description = newDescription;
                screenshotPrefix = newScreenshotPrefix;
            }
    
            public void Start()
            {
    
                animalDescriptions.Add(new AnimalDescription(
                    // animal name
                    "Of the Bear-Ape ARCTOPITHECUS.",
                    // animal description
                    "There is in America a very deformed beast which the inhabitants call Haut or Hauti, and the Frenchmen, Guenon, " +
                    "as big as a great African Munkey. His belly hangeth very low, his head and face like unto a childs, as may be seen by " +
                    "this lively picture, and being taken it will fight like a young child. His skin is of an ash-colour, and hairy like a Bear; " +
                    "he hath but three claws on a foot, as long as four fingers, and like the thornes of Privet, where-by he climeth up into the " +
                    "highest trees, and for the most part liveth of the leaves of a certain tree being of an exceeding height, which the Americans " +
                    "call Amahut, and thereof this beast is called Haut. Their tail is about three fingers long, having very little hair there-on; " +
                    "I observed, that although it often rained, yet was that beast never wet.",
                    // screenshot prefix
                    "ARCTOPITHECUS_"
                    ));
                animalDescriptions.Add(new AnimalDescription(
                    // animal name
                    "Of the SIMIVULPA, or Apifb-Fox.",
                    // animal description
                    "…they have seen a four-footed beast, the forepart like a Fox, and in the hinder part like an Ape, except that it had a mans " +
                    "feet, and ears like a Bat, and underneath the common belly, there was a skin like a bag or scrip, where-in she keepeth, lodgeth, " +
                    "and carryeth her young ones, until they are able to provide for themselves, without the help of their dam; neither do they come " +
                    "forth of that receptacle, except it be to suck milk, or sport themselves, so that the same under-belly is her best remedy against " +
                    "the furious Hunters, and other ravening beasts, to preserve her young ones, for she is incredibly swift, running with that carriage " +
                    "as if she has no burden. It hath a tail like a Munkey…",
                    // screenshot prefix
                    "SIMIVULPA_"
                    ));
                animalDescriptions.Add(new AnimalDescription(
                    // animal name
                    "The SCYTHIAN WOLF.",
                    // animal description
                    "…they have seen a four-footed beast, the forepart like a Fox, and in the hinder part like an Ape, except that it had a mans " +
                    "feet, and ears like a Bat, and underneath the common belly, there was a skin like a bag or scrip, where-in she keepeth, lodgeth, " +
                    "and carryeth her young ones, until they are able to provide for themselves, without the help of their dam; neither do they come " +
                    "forth of that receptacle, except it be to suck milk, or sport themselves, so that the same under-belly is her best remedy against " +
                    "the furious Hunters, and other ravening beasts, to preserve her young ones, for she is incredibly swift, running with that carriage " +
                    "as if she has no burden. It hath a tail like a Munkey…",
                    // screenshot prefix
                    "SCYTHIAN_WOLF_"
                    ));
                animalDescriptions.Add(new AnimalDescription(
                    // animal name
                    "Of the TATUS, or Guinean Beast.",
                    // animal description
                    "This is a four-footed strange Beast, it is naturally covered with a hard shell, divided and interlined like the fins of fishes, " +
                    "outwardly seeming buckled to the back like Coat-armor, within which the beast draweth up his body, as a Hedge-hog doth within his " +
                    "prickled skin; and therefore I take it to be a Brasilian Hedge-hog. It is not much greater than a little Pig, and by the snout, ears, " +
                    "legs, and feet thereof, it seemeth to be of that kind, saving that the snout is a little broader, and shorter than a Pigs, and the " +
                    "tail very long like a Lizards or Rats, and one of these being brought into France, did live upon the eating of seeds, and fruits of " +
                    "the Gardens, but it appeareth by that picture, or rather the stuffed, which Adriausus Mercellus the Apothecary…that the feet thereof " +
                    "are not cloven into two parts like Swine, but rather into many like Dogs, for upon the hinderfeet there are five toes, and upon the " +
                    "fore feet four, whereof two are so small that they are scarce visible. The breadth of that same skin was about seven fingers, and the " +
                    "length of it two spans, the shell or crust upon the back of it did not reach down unto the rump or tail, but broke off as it were upon " +
                    "the hips, some four fingers from the tail.",
                    // screenshot prefix
                    "TATUS_"
                    ));
                animalDescriptions.Add(new AnimalDescription(
                    // animal name
                    "Of the GULON",
                    // animal description
                    "This Beast was not known by the Ancients, but hath been since discovered in the Northern parts of the World, and because of the " +
                    "voracity thereof, it is called  (Gula)…is thought to be engendered by a Hyena and a Lioness, for the quality it resembleth a Hiena, " +
                    "and it is the same which is called (Crocuta;) it is a devouring and an unprofitable creature, having sharper teeth than other creatures. " +
                    "Some think it is derived of a Wolf and a Dog, for it is about the bigness of a Dog; it hath the face of Cat, the body and tail of a Fox; " +
                    "being black of colour; his feet and nails be most sharp, his skin rusty, the hair very sharp, and it feedeth upon dead carkases. When it " +
                    "hath found a dead carcass he eateth thereof so violently, that his belly standeth out like a bell; then he seeketh for some narrow passage " +
                    "betwixt two trees, and there draweth through his body, by pressing whereof, he driveth out the meat which he had eaten; and being so emptied " +
                    "returneth and devoureth as much as he did before, and goeth again and emptieth himself as in former manner; and so continueth eating and " +
                    "emptying till all be eaten.",
                    // screenshot prefix
                    "GULON_"
                    ));
                animalDescriptions.Add(new AnimalDescription(
                    // animal name
                    "Of the SUCCORATH",
                    // animal description
                    "…it is of a very deformed shape, and monstrous presence, a great ravener and untamable wilde Beast. When the Hunters that desire her " +
                    "skin set upon her, she flyeth very swift, carrying her young ones upon her back, and covering them with her broad tail: Hunters dig " +
                    "several pits or great holes in the earth, which they cover with boughs, sticks, and earth, so weakly that if the Beast chance at any " +
                    "time to come upon it, she and her young ones fall down into the pit and are taken. This cruel, untamable, impatient, violent, ravening, " +
                    "and bloudy beast, perceiving that her natural strength cannot deliver her from the wit and policy of men her hunters, (for being inclosed " +
                    "she can never get out again.)…she destroyeth them all with her own teeth; for there was never any of them taken alive…And this is all I " +
                    "finde recorded of this most savage Beast.",
                    // screenshot prefix
                    "SUCCORATH_"
                    ));
    
                RandomizeAnimals();
            }
    
            void RandomizeAnimals()
            {
                System.Random rand = new System.Random();
                foreach (AnimalDescription animalDescription in animalDescriptions)
                {
                    animalDescription.randomNumber = rand.Next();
                }
    
                animalDescriptions.Sort((firstObj, secondObj) => {
                    return firstObj.randomNumber.CompareTo(secondObj.randomNumber);
                });
    
                //or
                //animalDescriptions = animalDescriptions.OrderBy(x => x.randomNumber).ToList();
    
            }
    
    
        }
    }
    

    尝试在游戏对象上添加它会起作用。

    【讨论】:

    • 感谢指正。你能告诉我空方法的意义是什么:public AnimalDescription() {}?这在宏伟的计划中是如何运作的?以及如何运行这个脚本?我以前没有使用过命名空间。我试着把: void Start () { ConsoleApplication1.Program();在另一个脚本中运行该脚本,但它给出了错误:错误 CS0119:表达式表示 type', where a variable',value' or method group' 是预期的。我该如何解决这个问题?
    • 在这个脚本中,我只修复了“无法添加脚本行为 AnimalDescription。脚本需要从 MonoBehaviour 派生!”仅错误。出现此错误的原因是,要将任何脚本添加到任何游戏对象,您必须从 MonoBehaviour 类派生它。关于空方法:public AnimalDescription() { },我会说,您应该使用“jdweng”更新脚本,因为它在您的情况下没有意义。关于命名空间,您应该在这里阅读统一文档link
    • 无论如何,如果你想避免使用命名空间,你可以,它仍然会像一个魅力。
    【解决方案3】:

    试试这个。完整的解决方案。我有两种不同的解决方案,在 Start() 方法中略有不同。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                AnimalDescription animalDescription = new AnimalDescription();
                animalDescription.Start();
            }
        }
        public class AnimalDescription
        {
            public string name { get; set; }
            public string description { get; set; }
            public string screenshotPrefix { get; set; }
            private int randomNumber;
            static List<AnimalDescription> animalDescriptions = new List<AnimalDescription>();
    
    
            public void Start()
            {
    
                animalDescriptions.Add(new AnimalDescription() {
    
                    name = "Of the Bear-Ape ARCTOPITHECUS.",
                    description = "There is in America a very deformed beast which the inhabitants call Haut or Hauti, and the Frenchmen, Guenon, " +
                    "as big as a great African Munkey. His belly hangeth very low, his head and face like unto a childs, as may be seen by " +
                    "this lively picture, and being taken it will fight like a young child. His skin is of an ash-colour, and hairy like a Bear; " +
                    "he hath but three claws on a foot, as long as four fingers, and like the thornes of Privet, where-by he climeth up into the " +
                    "highest trees, and for the most part liveth of the leaves of a certain tree being of an exceeding height, which the Americans " +
                    "call Amahut, and thereof this beast is called Haut. Their tail is about three fingers long, having very little hair there-on; " +
                    "I observed, that although it often rained, yet was that beast never wet.",
                    screenshotPrefix = "ARCTOPITHECUS_"
                });
                animalDescriptions.Add(new AnimalDescription(){
                    name = "Of the SIMIVULPA, or Apifb-Fox.",
                    description = "…they have seen a four-footed beast, the forepart like a Fox, and in the hinder part like an Ape, except that it had a mans " +
                    "feet, and ears like a Bat, and underneath the common belly, there was a skin like a bag or scrip, where-in she keepeth, lodgeth, " +
                    "and carryeth her young ones, until they are able to provide for themselves, without the help of their dam; neither do they come " +
                    "forth of that receptacle, except it be to suck milk, or sport themselves, so that the same under-belly is her best remedy against " +
                    "the furious Hunters, and other ravening beasts, to preserve her young ones, for she is incredibly swift, running with that carriage " +
                    "as if she has no burden. It hath a tail like a Munkey…",
                    screenshotPrefix = "SIMIVULPA_"
                });
                animalDescriptions.Add(new AnimalDescription() {
                    name = "The SCYTHIAN WOLF.",
                    description = "…they have seen a four-footed beast, the forepart like a Fox, and in the hinder part like an Ape, except that it had a mans " +
                    "feet, and ears like a Bat, and underneath the common belly, there was a skin like a bag or scrip, where-in she keepeth, lodgeth, " +
                    "and carryeth her young ones, until they are able to provide for themselves, without the help of their dam; neither do they come " +
                    "forth of that receptacle, except it be to suck milk, or sport themselves, so that the same under-belly is her best remedy against " +
                    "the furious Hunters, and other ravening beasts, to preserve her young ones, for she is incredibly swift, running with that carriage " +
                    "as if she has no burden. It hath a tail like a Munkey…",
                    screenshotPrefix = "SCYTHIAN_WOLF_"
                });
                animalDescriptions.Add(new AnimalDescription() {
                    name = "Of the TATUS, or Guinean Beast.",
                    description = "This is a four-footed strange Beast, it is naturally covered with a hard shell, divided and interlined like the fins of fishes, " +
                    "outwardly seeming buckled to the back like Coat-armor, within which the beast draweth up his body, as a Hedge-hog doth within his " +
                    "prickled skin; and therefore I take it to be a Brasilian Hedge-hog. It is not much greater than a little Pig, and by the snout, ears, " +
                    "legs, and feet thereof, it seemeth to be of that kind, saving that the snout is a little broader, and shorter than a Pigs, and the " +
                    "tail very long like a Lizards or Rats, and one of these being brought into France, did live upon the eating of seeds, and fruits of " +
                    "the Gardens, but it appeareth by that picture, or rather the stuffed, which Adriausus Mercellus the Apothecary…that the feet thereof " +
                    "are not cloven into two parts like Swine, but rather into many like Dogs, for upon the hinderfeet there are five toes, and upon the " +
                    "fore feet four, whereof two are so small that they are scarce visible. The breadth of that same skin was about seven fingers, and the " +
                    "length of it two spans, the shell or crust upon the back of it did not reach down unto the rump or tail, but broke off as it were upon " +
                    "the hips, some four fingers from the tail.",
                    screenshotPrefix = "TATUS_"
                });
                animalDescriptions.Add(new AnimalDescription() {
                    name = "Of the GULON",
                    description = "This Beast was not known by the Ancients, but hath been since discovered in the Northern parts of the World, and because of the " +
                    "voracity thereof, it is called  (Gula)…is thought to be engendered by a Hyena and a Lioness, for the quality it resembleth a Hiena, " +
                    "and it is the same which is called (Crocuta;) it is a devouring and an unprofitable creature, having sharper teeth than other creatures. " +
                    "Some think it is derived of a Wolf and a Dog, for it is about the bigness of a Dog; it hath the face of Cat, the body and tail of a Fox; " +
                    "being black of colour; his feet and nails be most sharp, his skin rusty, the hair very sharp, and it feedeth upon dead carkases. When it " +
                    "hath found a dead carcass he eateth thereof so violently, that his belly standeth out like a bell; then he seeketh for some narrow passage " +
                    "betwixt two trees, and there draweth through his body, by pressing whereof, he driveth out the meat which he had eaten; and being so emptied " +
                    "returneth and devoureth as much as he did before, and goeth again and emptieth himself as in former manner; and so continueth eating and " +
                    "emptying till all be eaten.",
                    screenshotPrefix = "GULON_"
                });
                animalDescriptions.Add(new AnimalDescription() {
                    name = "Of the SUCCORATH",
                    description = "…it is of a very deformed shape, and monstrous presence, a great ravener and untamable wilde Beast. When the Hunters that desire her " +
                    "skin set upon her, she flyeth very swift, carrying her young ones upon her back, and covering them with her broad tail: Hunters dig " +
                    "several pits or great holes in the earth, which they cover with boughs, sticks, and earth, so weakly that if the Beast chance at any " +
                    "time to come upon it, she and her young ones fall down into the pit and are taken. This cruel, untamable, impatient, violent, ravening, " +
                    "and bloudy beast, perceiving that her natural strength cannot deliver her from the wit and policy of men her hunters, (for being inclosed " +
                    "she can never get out again.)…she destroyeth them all with her own teeth; for there was never any of them taken alive…And this is all I " +
                    "finde recorded of this most savage Beast.",
                    screenshotPrefix = "SUCCORATH_"
                });
    
                RandomizeAnimals();
            }
    
            void RandomizeAnimals()
            {
                System.Random rand = new System.Random();
                foreach (AnimalDescription animalDescription in animalDescriptions)
                {
                    animalDescription.randomNumber = rand.Next();
                }
    
                animalDescriptions.Sort((firstObj, secondObj) =>
                {
                    return firstObj.randomNumber.CompareTo(secondObj.randomNumber);
                });
    
                //or
                //animalDescriptions = animalDescriptions.OrderBy(x => x.randomNumber).ToList();
    
            }
    
    
        }
    }
    ​
    

    去掉 start 中的 Add() 方法

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                AnimalDescription animalDescription = new AnimalDescription();
                animalDescription.Start();
            }
        }
        public class AnimalDescription
        {
            public string name { get; set; }
            public string description { get; set; }
            public string screenshotPrefix { get; set; }
            private int randomNumber;
            static List<AnimalDescription> animalDescriptions = new List<AnimalDescription>();
    
    
            public void Start()
            {
                animalDescriptions = new List<AnimalDescription>() {
                    new AnimalDescription() {
                        name = "Of the Bear-Ape ARCTOPITHECUS.",
                        description = "There is in America a very deformed beast which the inhabitants call Haut or Hauti, and the Frenchmen, Guenon, " +
                        "as big as a great African Munkey. His belly hangeth very low, his head and face like unto a childs, as may be seen by " +
                        "this lively picture, and being taken it will fight like a young child. His skin is of an ash-colour, and hairy like a Bear; " +
                        "he hath but three claws on a foot, as long as four fingers, and like the thornes of Privet, where-by he climeth up into the " +
                        "highest trees, and for the most part liveth of the leaves of a certain tree being of an exceeding height, which the Americans " +
                        "call Amahut, and thereof this beast is called Haut. Their tail is about three fingers long, having very little hair there-on; " +
                        "I observed, that although it often rained, yet was that beast never wet.",
                        screenshotPrefix = "ARCTOPITHECUS_"
                    },
                    new AnimalDescription() {
                        name = "Of the SIMIVULPA, or Apifb-Fox.",
                        description = "…they have seen a four-footed beast, the forepart like a Fox, and in the hinder part like an Ape, except that it had a mans " +
                        "feet, and ears like a Bat, and underneath the common belly, there was a skin like a bag or scrip, where-in she keepeth, lodgeth, " +
                        "and carryeth her young ones, until they are able to provide for themselves, without the help of their dam; neither do they come " +
                        "forth of that receptacle, except it be to suck milk, or sport themselves, so that the same under-belly is her best remedy against " +
                        "the furious Hunters, and other ravening beasts, to preserve her young ones, for she is incredibly swift, running with that carriage " +
                        "as if she has no burden. It hath a tail like a Munkey…",
                        screenshotPrefix = "SIMIVULPA_"
                    },
                    new AnimalDescription() {
                        name = "The SCYTHIAN WOLF.",
                        description = "…they have seen a four-footed beast, the forepart like a Fox, and in the hinder part like an Ape, except that it had a mans " +
                        "feet, and ears like a Bat, and underneath the common belly, there was a skin like a bag or scrip, where-in she keepeth, lodgeth, " +
                        "and carryeth her young ones, until they are able to provide for themselves, without the help of their dam; neither do they come " +
                        "forth of that receptacle, except it be to suck milk, or sport themselves, so that the same under-belly is her best remedy against " +
                        "the furious Hunters, and other ravening beasts, to preserve her young ones, for she is incredibly swift, running with that carriage " +
                        "as if she has no burden. It hath a tail like a Munkey…",
                        screenshotPrefix = "SCYTHIAN_WOLF_"
                    },
                    new AnimalDescription() {
                        name = "Of the TATUS, or Guinean Beast.",
                        description = "This is a four-footed strange Beast, it is naturally covered with a hard shell, divided and interlined like the fins of fishes, " +
                        "outwardly seeming buckled to the back like Coat-armor, within which the beast draweth up his body, as a Hedge-hog doth within his " +
                        "prickled skin; and therefore I take it to be a Brasilian Hedge-hog. It is not much greater than a little Pig, and by the snout, ears, " +
                        "legs, and feet thereof, it seemeth to be of that kind, saving that the snout is a little broader, and shorter than a Pigs, and the " +
                        "tail very long like a Lizards or Rats, and one of these being brought into France, did live upon the eating of seeds, and fruits of " +
                        "the Gardens, but it appeareth by that picture, or rather the stuffed, which Adriausus Mercellus the Apothecary…that the feet thereof " +
                        "are not cloven into two parts like Swine, but rather into many like Dogs, for upon the hinderfeet there are five toes, and upon the " +
                        "fore feet four, whereof two are so small that they are scarce visible. The breadth of that same skin was about seven fingers, and the " +
                        "length of it two spans, the shell or crust upon the back of it did not reach down unto the rump or tail, but broke off as it were upon " +
                        "the hips, some four fingers from the tail.",
                        screenshotPrefix = "TATUS_"
                    },
                    new AnimalDescription() {
                        name = "Of the GULON",
                        description = "This Beast was not known by the Ancients, but hath been since discovered in the Northern parts of the World, and because of the " +
                        "voracity thereof, it is called  (Gula)…is thought to be engendered by a Hyena and a Lioness, for the quality it resembleth a Hiena, " +
                        "and it is the same which is called (Crocuta;) it is a devouring and an unprofitable creature, having sharper teeth than other creatures. " +
                        "Some think it is derived of a Wolf and a Dog, for it is about the bigness of a Dog; it hath the face of Cat, the body and tail of a Fox; " +
                        "being black of colour; his feet and nails be most sharp, his skin rusty, the hair very sharp, and it feedeth upon dead carkases. When it " +
                        "hath found a dead carcass he eateth thereof so violently, that his belly standeth out like a bell; then he seeketh for some narrow passage " +
                        "betwixt two trees, and there draweth through his body, by pressing whereof, he driveth out the meat which he had eaten; and being so emptied " +
                        "returneth and devoureth as much as he did before, and goeth again and emptieth himself as in former manner; and so continueth eating and " +
                        "emptying till all be eaten.",
                        screenshotPrefix = "GULON_"
                    },
                    new AnimalDescription() {
                        name = "Of the SUCCORATH",
                        description = "…it is of a very deformed shape, and monstrous presence, a great ravener and untamable wilde Beast. When the Hunters that desire her " +
                        "skin set upon her, she flyeth very swift, carrying her young ones upon her back, and covering them with her broad tail: Hunters dig " +
                        "several pits or great holes in the earth, which they cover with boughs, sticks, and earth, so weakly that if the Beast chance at any " +
                        "time to come upon it, she and her young ones fall down into the pit and are taken. This cruel, untamable, impatient, violent, ravening, " +
                        "and bloudy beast, perceiving that her natural strength cannot deliver her from the wit and policy of men her hunters, (for being inclosed " +
                        "she can never get out again.)…she destroyeth them all with her own teeth; for there was never any of them taken alive…And this is all I " +
                        "finde recorded of this most savage Beast.",
                        screenshotPrefix = "SUCCORATH_"
                    }
                };
    
                RandomizeAnimals();
            }
    
            void RandomizeAnimals()
            {
                System.Random rand = new System.Random();
                foreach (AnimalDescription animalDescription in animalDescriptions)
                {
                    animalDescription.randomNumber = rand.Next();
                }
    
                animalDescriptions.Sort((firstObj, secondObj) =>
                {
                    return firstObj.randomNumber.CompareTo(secondObj.randomNumber);
                });
    
                //or
                //animalDescriptions = animalDescriptions.OrderBy(x => x.randomNumber).ToList();
    
            }
    
    
        }
    }
    ​
    

    【讨论】:

    • 谢谢!但是我遇到了问题 - 当我将脚本拖到游戏对象上时,我收到错误:无法添加脚本行为 AnimalDescription。脚本需要从 MonoBehaviour 派生!我该如何解决这个问题?
    • 不是 Java 专家。修改代码以使 List 静态。
    • 我做了属性 {get;放;}。然后将您的 cmets "name"、"description"、"screenshotPrefix" 更改为属性名称。移除构造函数
    • 感谢所有这些!您有时间解释一下 RandomizeAnimals 函数中发生了什么吗?我只是在做一些事情,我很想知道一切是如何运作的。如何访问和调试以查看当前选择了 List 中的哪个元素并打印出元素中的每个字段(以便我以后可以将这些字段分配给文本组件)?换句话说,在我正在开发的游戏中,我想一次只选择一种动物描述(每场比赛)。
    • 你能告诉我空方法的意义是什么:public AnimalDescription() { }?这在宏伟的计划中是如何运作的?以及如何运行这个脚本?我以前没有使用过命名空间。我试着把: void Start () { ConsoleApplication1.Program();在另一个脚本中运行该脚本,但它给出了错误:错误 CS0119:表达式表示 type', where a variable',value' or method group' 是预期的。我该如何解决这个问题?
    猜你喜欢
    • 2016-02-12
    • 1970-01-01
    • 2016-03-02
    • 1970-01-01
    • 2017-06-22
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    相关资源
    最近更新 更多