How can I add or subtract from a variable in a Mathf.Clamp sequence?

I have a 2D slingshot working in my game so that when the player clicks on the character, pulls them back and releases, they are shot into the air. To limit the distance the character can be pulled back I am currently using this section of code:

transform.position.x = Mathf.Clamp(transform.position.x, -35, -28);

transform.position.y = Mathf.Clamp(transform.position.y, 33, 40);

This works fine, but I am planning on having multiple stages and would like to have the distance the character can be pulled set to the same distance every time. It would be nice if I could simply drop in the object the character is launching from and have the code apply no matter where I place it. However, when I try to clamp the distance based on the location of the object, it won’t let me. The code I am trying to use for that looks something like this:

transform.position.x = Mathf.Clamp(transform.position.x, (GameObject.Find(“spawnPoint”) - 5), (GameObject.Find(“spawnPoint”) + 5);

transform.position.y = Mathf.Clamp(transform.position.y, (GameObject.Find(“spawnPoint”) - 5), (GameObject.Find(“spawnPoint”) + 5);

I appreciate any suggestions.

Try caching all the data you are using ahead of time. Something like this:

var newPosition : Vector3 = transform.position;
var spawnPoint : GameObject = GameObject.Find("spawnPoint");

Now use ‘newPosition’ and ‘spawnPoint’ wherever you would have used the original values, and at the end use

transform.position = newPosition;

to save the changes.