I’m trying to make the apple trackpad work with unity. I know there’s one in the asset store but I want to see if I can do it myself. I’ve already got the part working where the os x plugin sends the touch data to my unity c# script, but now I want to create a new Touch(). The problem is things like the position variables in the Touch class are all read only. And there’s not really a solution in the documentation either. I could of course create my own touch class, but using the default unity one seems a lot cleaner and faster. Does anyone know how to create a custom Touch? Perhaps through the constructor or maybe there’s a function to set the position?
Alright so it turns out there is no way to set the touch position trough the scripting api, but since have access to pretty much all c# functions you can use some trickery to set the position. Here’s how I did it.
First you have to find all the fields that the Touch class has (source)
var fields = typeof(Touch).GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
var names = Array.ConvertAll(fields, field => field.Name);
foreach(var name in names){
print(name);
}
this prints all the fields of the Touch class
as you can see m_Position is the name of the position field. But it’s private so you can’t set it trough myTouchVar.m_Position = new Vector2(0f,10f);
I kinda drove me bats that Touch was sealed up like that so I handle this by making my own MicroTouch object that has a “Gather all touches” method on it, which can include the mouse right alongside the touches, all “abstracted” to an array of MicroTouch objects.
You can get the full source to the project that tests it all out here:
Dig into the directory a bit and look for MicroTouch.cs and check the code for how it is used. You basically gather an array, then iterate it. Perhaps this will help you.
Thanks, Yeah I think making a customisable Touch class is the best option here, I’m not sure why I’m so obsessed with trying to modify a touch object. Perhaps it’s because with a custom touch class I have to convert the Input.touches to the custom class for devices that don’t use a trackpad, which is a bit slower.
By the way that thing I said earlier turned out to not be working. Modifying the position that way actually doesn’t do anything at all.