Hi UA,
I’m trying to compare a dynamic string value in one class to a fixed string variable in another class using the observer design pattern. (go easy, I’m only just getting my head around design patterns)
Quick side note: When I started this project I was doing the string comparisons within the FrameCounter class, what is now the publisher. Once that was working I wanted to push the comparisons out to their own classes so I can add/remove them dynamically.
While the publisher’s dynamic string variable is getting to the subscriber class, the subscriber class is not performing the comparison, therefore even when the strings match, the function call under the ‘if’ statement is not called.
//publisher class
public class FrameCounter : MonoBehaviour
{
public string buttonCombination;
public delegate void ButtonInput(string inputTemp);
public event ButtonInput buttInpEvent;
}
if(buttInpEvent != null)
{
buttInpEvent(buttonCombination);
}
//subscriber class
void Start ()
{
FindObjectOfType<FrameCounter>().buttInpEvent += SetInput;
}
void SetInput( string inpTmp)
{
input = inpTmp;
}
void Update ()
{
print(input);
if(string.CompareOrdinal(input, "7651") == 0 || string.CompareOrdinal(input, "765B") == 0)
{
//do something
}
}
I’ve included print(input) in the subscriber class; so I can see that the ‘input’ variable is definitely the same as the ‘buttonCombination’ variable of the publisher class.
Some things I’ve tried:
- Placed the string comparison in a function that is only called once (as opposed to every frame). Nothing.
- Instead of using an observer pattern I’ve tried creating a FrameCounter variable in the the class I want to do the string comparison in. Still doesn’t work.
- I’ve tried various types of string comparison (==, .Equals etc) still nothing.
- For the sake of elimination I have hard-coded the ‘input’ variable to be correct and that works.
- Also for the sake of testing, I abandoned any OOP ideas all together and placed the string comparison back inside the FrameCounter class, that string comparison worked fine.
- I have hard-coded buttonCombination to the correct string and then called buttInpEvent(buttonCombination) in the Start() function of the FrameCounter class (and removed any code that changes buttonCombination dynamically). The string comparison is still not successful.
FYI the buttonCombination string in FrameCounter is modified fifty times a second in FixedUpdate(), but moving where buttonCombination is set to Update() makes no difference, in fact it doesn’t even matter if it’s only set once in the Start() function (see 6).
I’m using CompareOrdinal because it is much faster than simply using ‘==’. Once I got the comparisons working within one class I needed to push the comparisons out to individual classes so I can add and remove the classes dynamically.
If there’s a better way to compare a dynamic string in one class to a fixed string in another, I’m willing to try it.
Cheers,