unity中使用C#类,构造方法,集合,命名空间并调用

C#mainplayer.cs代码如下:

using JetBrains.Annotations;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//引入
using Assets.Creator_Kit___Beginner_Code.Scripts.myclass;

public class MainPlayer : MonoBehaviour
{
    // Start is called before the first frame update
    //单独调用
    public Cat cat0;
    public Dog dog;
    
    void Start()
    {

        cat0.Print();
        cat0.Perr();
        dog.Perr();

        List<Cat> cats = new List<Cat>();
        for (int i = 1; i < 100; i++) {
            cats.Add(new Cat($"这是第{i}只猫",i));
        }
        foreach (Cat cat in cats) {
            cat.Perr();
            cat.Print();
        }

    }

    // Update is called once per frame
    
}
//创建Cat类
[Serializable]
public class Cat{
    public string catname;
    public int catage;
    
    
    //构造方法
    public Cat(string catname, int catage)
    {
        this.catname = catname;
        this.catage = catage;
    }

    public void Print() {
        Debug.Log($"这只猫的名字叫{catname},它今年{catage}岁了!");
    }
    public void Perr()
    {

        Debug.Log($"{catname},一直在不停的喵喵叫。。。。。");
    }

}


//



c# Dog.cs代码:

using System;
using System.Collectns.Generic;
using System.Diagnostics;
using System.Linq;
using UnityEngine;
using System.Text;
using System.Threading.Tasks;

namespace Assets.Creator_Kit___Beginner_Code.Scripts.myclass
{
    [Serializable]
    public class Dog
    {
        public string name;
        public int age;
        public Dog(string name, int age) {
            this.name = name;
            this.age = age;

        }
        public void Perr() {
            UnityEngine.Debug.Log($"这只狗的名字叫{name},今年{age}岁了。");
        }
    }
}

单独调用:

![在这里插入图片描述](https://img-blog.csdnimg.cn/52c63c726d254249a798083fc10b3f24.png
运行结果:
在这里插入图片描述

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值