###前提・実現したいこと
以下のコードでchartest型のListの内容を変化させた時、すべてのchartest型Listに適用されてしまいます。同じものを参照しているからでしょうか?
共有させない方法がありますか?
具体的に言うとcccとcceeのmoveが別の結果になる方法がありますか?
###発生している問題・エラーメッセージ
エラーメッセージはありません
###該当のソースコード
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4using UnityEngine.UI; 5using UnityEngine.EventSystems; 6 7public class GameManager : MonoBehaviour { 8 9 public List<chartest> EEEEEEE = new List<chartest>(); 10 11 public Decktest ddd; 12 public chartest ccc; 13 public chartest ccee; 14 15 void Start () { 16 ddd = new Decktest(); 17 ddd.AllAdd(); 18 ddd.firstDekkiInit(); 19 //EEEEEEE = new List<chartest>(ddd.mydekki); 20 //データ追加 21 EEEEEEE.Add(ddd.chars[0]); 22 EEEEEEE.Add(ddd.chars[1]); 23 EEEEEEE.Add(ddd.chars[2]); 24 //テスト1 25 ccc = ddd.mydekki[1]; 26 ccee = EEEEEEE[1]; 27 28 ccc.Move_skills(ddd.chars[2].move); 29 30 Debug.Log("start test1"); 31 Debug.Log("ccc"); 32 for(int i = 0;i<8;i++){ 33 Debug.Log(ccc.move[i]); 34 } 35 Debug.Log(ccee"); 36 for(int i = 0;i<8;i++){ 37 Debug.Log(ccee.move[i]); 38 } 39 //テスト2 40 ccc2 = ddd.mydekki[0]; 41 ccee2 = EEEEEEE[0]; 42 43 ccc2.InitStatus(ddd.chars[2]); 44 Debug.Log("start test2"); 45 Debug.Log("ccc"); 46 for(int i = 0;i<8;i++){ 47 Debug.Log(ccc2.move[i]); 48 } 49 Debug.Log("ccee"); 50 for(int i =0 ;i<8;i++){ 51 Debug.Log(ccee2.move[i]); 52 } 53 54 } 55} 56
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Decktest : MonoBehaviour { public List<chartest> chars = new List<chartest>(); public List<chartest> mylist = new List<chartest>(); public List<chartest> mydekki = new List<chartest>(); public void firstDekkiInit(){ mylist.Add(chars[0]); mylist.Add(chars[1]); mylist.Add(chars[2]); foreach(var v in mylist){ mydekki.Add(v); } } public void AllAdd(){ chars.Add (new chartest (1,0,0,0,0,0,0,0)); chars.Add (new chartest (0,8,0,8,0,8,0,8)); chars.Add (new chartest (1,1,1,1,1,1,1,1)); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class chartest :MonoBehaviour{ public int[] move = new int[8]; public chartest(int N,int NE,int E,int SE,int S,int SW,int W,int NW){ move[0] = N; move[1] = NE; move[2] = E; move[3] = SE; move[4] = S; move[5] = SW; move[6] = W; move[7] = NW; } public void InitStatus(chartest t){ this.move = t.move; } public void Move_skills(int[] m){ for(int y = 0;y<8;y++){ this.move[y] = this.move[y] + m[y]; if(move[y]>8) move[y] = 8; } } }
###試したこと
参照が同じなのが原因かと思い、値渡しでEEEEEEEを作成してみましたが同じ結果でしたGamemanagerクラスでコメントアウトしているコードがそれにあたります。
また、質問用コードでは再現できませんでしたが、実際の環境ではchartestクラスのInitStatus()でmoveを変更させた時は別の結果になりました。
Move_Skillsによるmoveの変更方法ではcccとcceeの内容が共有されてしまいます。
###補足情報(言語/FW/ツール等のバージョンなど)
unity 2017.2.0f3 Personal
C#
Start()結果
start test1
ccc
1
8
1
8
1
8
1
8
ccee
1
8
1
8
1
8
1
8
start test2
ccc
1
1
1
1
1
1
1
1
ccee
1
1
1
1
1
1
1
1
不足していることや解決のために足りない情報があればお伝えします。
宜しくお願いします。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/12/27 12:27