Keeping the player to be within the screen

Hi!

Mine is 2D app.
The player moves only up and down.
The screen has a ground sprite. Its height is 300 pixels(0.3f).

I want to keep this player to be within the screen, because it flies out of the upper border of the screen.
When I click the play button, the debugging in console says;

‘error cs0118: UnityEngine.Component.transform’ is a 'property but a ‘type was expected’

How to fix this? Your help will be very appreciated.

The script as follows;

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Boundary: Monobehaviour
{
public transform target;
Camera cam;
Vector3 pos = Camera.WorldToViewportPoint(transform.position);

void Start()
{
cam = GetComponent();
}

void Update()
{
if ( pos.y < 0.3f ) pos.y = 0.3f;
if ( pos.y < 1f ) pos.y = 1f;

transform.position = Camera.ViewportToWorldPoint(pos);
}

Replace this

public transform target;

with this

public Transform target;

Also, please use code tags here on the forums. And I’m not sure why you even have this., you don’t use the ‘target’ anywhere.

Hi,LurkingNinjaDev
Thank you for your help.

I replaced “t” by “T” according to your instruction, but no changes.
And I don’t understand what the “unsing target” means. Where to use it?
Please let me know it in detailed scripts.

Thank you again.

Please put your code in code tags here on the forum!

Also, are you sure about this?

if ( pos.y < 0.3f ) pos.y = 0.3f;
if ( pos.y < 1f ) pos.y = 1f;

It’s redundant, because .3f is always < than 1f.
I’m guessing that you ment

if ( pos.y < 0.3f ) pos.y = 0.3f;
if ( pos.y > 1f ) pos.y = 1f;

Hi, LurkingNinjaDev

I am sorry for not putting code in code tags. I did not know that. I will do it in the future thread.
And I don’t understand why there is a duplicate of this thread. Probably because of my mistake.
I want to delete the duplicate, if possible ,or you can delete the duplicate.

Anyway,I corrected the script according to your above instruction, not any change but the same situation.

Thank you very much.

You can put your code in code tags by clicking this icon in the “Rich Text Editor”:

A small popup overlay will open (see below). Enter your code in the “Code” textbox and hit the “Insert” button :slight_smile:

As for the duplicated thread: It got closed already, don’t worry.