Tuple of 2 Int and contain method in Unity C#
Asked Answered
I

3

6

Trying to make a list tuple of two Integers and after that adding something in it. Then comparing if x,y is one of the tuples in list tuple.

List<Tuple<int, int>> monsterPositions;

I instantly get error like this that it doesn't have Tuple:

Assets/TimeMap.cs(20,7): error CS0246: The type or namespace name `Tuple' could not be found. Are you missing an assembly reference?

I found out that I can add inside tuple like this:

monsterPositions.Add(randomX, randomY);

Then the hardest part is how can I compare the x and y in my Tuple list. I am trying to use Contains but I don't know what is wrong with it.

monsterPositions.Contains(Tuple(x, y));
Illegitimacy answered 24/10, 2017 at 6:57 Comment(6)
do you have using System; at top of your cs file?Affluence
I have using System.Collections; using System.Collections.Generic; using UnityEngine;Illegitimacy
then add using System;, its needed for Tuple.Affluence
Unity does not support Tuples.Pariah
@S.Akbari What do you suggest to use then?Illegitimacy
Why not use your own class or struct, implementing equality appropriately? That would be cleaner to use anyway, as then you'd have appropriate X and Y properties instead of just Item1 and Item2.Petrinapetrine
Z
7

Pulling out @S.Akbari's comment on the question as I almost missed it when looking through:

Unity does not support Tuples.

Still the case in Unity 2017.3.1f1.

Other observations:

  • You can use Vector2 or Vector2Int (and the other numbers) if you're just storing floats and ints.
  • I noticed that UniRx has Tuple support, if you're using that o.O
  • Best follow @Jon Skeet's advice and make your own class or struct otherwise, or like he mentioned, to implement equality if necessary.
Zincography answered 9/3, 2018 at 13:34 Comment(0)
S
4

This is an ancient post, but in aid of those who may stumble upon it, as of 2020 Unity C# supports built-in tuple construction in a new way.

If you don't need the small overhead of Vector2Int, you can use the following declaration:

private (int,int) monsterPositions = (randomX,randomY); //assuming <T>randomX,Y == int

These int tuples can be stored as coordinate pairs in arrays or hashSets, and can be accessed with simple search or .Contains functions

Superintendent answered 23/10, 2020 at 14:22 Comment(0)
S
2

Change the player settings "API compatibility level" to ".NET 4.x":

Change API compatibility level to .NET 4.x

Sporozoite answered 15/1, 2019 at 13:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.