#💻┃code-beginner

1 messages · Page 368 of 1

rich adder
#

Assets -> Reimport ALL also should work when issues like this occur

spring tusk
#

The good new is it's not burning fuel like hell anymore,Coroutine runs only once. But it's still burns fuel even the engine is not on/ not clicking

#

Perhaps there is another problem with Input.GetMouseButtonDown(0)

swift crag
#

GetMouseButtonUp is true for one frame

#

You're probably missing it due to that WaitForSeconds.

rich adder
#

yeah the timing would have to be insane

swift crag
#

If you just want to know if the mouse button is now up, use GetMouseButton

#

if it's false, the mouse is not being pressed

swift sedge
rich adder
swift sedge
#

the guys that made resident evil?

rich adder
swift sedge
#
  • many others blushie
rich adder
#

indeed

#

streetfighter ehem

#

Capcom is def one of the most successful game company

swift sedge
#

we have to include resident evil 2, 3 and 4

rich adder
#

where is 1 ?

swift sedge
rich adder
#

wat?

spring tusk
rich adder
swift sedge
#

I mean in success

rich adder
#

not even close

#

EA got big because of Sport games, mainly publishing*

#

they had good games they Published but not made.
Notably Freedom Fighters and alike

#

dead space was good too

swift sedge
#

well, they have their own game engine at least

spring tusk
#

I miss dead space

rich adder
spring tusk
swift crag
#

So what? You can check if it’s currently pressed

#

You don’t need to know if it was released this frame

spring tusk
#

It's working for "flame", which appears on hold

swift crag
#

If GetMouseButton returns false, you aren’t holding the button

rich adder
#

wouldnt something like this work

#
no needed
spring tusk
#

lemme try

willow scroll
swift crag
rich adder
#

ahh yeah you're right

spring tusk
#

lemme try other

willow scroll
willow scroll
#

Both won't work in your case

spring tusk
#

It doesn't stop burning fuel

rich adder
swift crag
#

if you want to burn fuel until you let go of the mouse, all you need to do is use GetMouseButton, not GetMouseButtonUp

#

that's it

spring tusk
#

T_T

swift crag
#

you will need to invert the condition, of course

#
if (!Input.GetMouseButton(0))
#

this will succeed when the left mouse button is not being pressed

spring tusk
#

wait

willow scroll
swift crag
#

and yes, you should really just do this

spring tusk
swift crag
#

also, the for loop is really weird

#

just do

#
while (fuelAmount > 0 && Input.GetMouseButton(0)) {
  ...
}
spring tusk
#

It's not my code, got it from youtube

rich adder
#

yea this can probably be easily just in Update

willow scroll
swift crag
#

using a coroutine makes it easier to do the 0.2 second interval, I guess

#

but it'll also be inaccurate, since you'll get more than 0.2 second delays (because the coroutine actually resumes on the next frame after 0.2 seconds pass)

#

so yes, this really belongs in Update

#

You can use a float field to store how long until the next unit of fuel is burned

rich adder
#

time.time also can help do the intervals

swift crag
#
void Update() {
  bool burningFuel = Input.GetMouseButton(0) && fuelAmount > 0;
  if (burningFuel) {
    burnTimer -= Time.deltaTime;
    while (burnTimer <= 0) {
      fuelAmount -= 1;
      burnTimer += 0.2f;
    }
  }
}
willow scroll
swift crag
#

something like this

swift crag
#

Although, if you do want that, you'd need to rewrite it a bit

spring tusk
#

I am trying : )

#

But update makes much more sense

swift crag
#

Coroutines are useful for when you might be doing the same thing many times

#

where it'd be annoying to keep track of everything in fields and handle them all in Update

#

e.g. spawning a particle system and then destroying it after 3 seconds

#

(although, in that case, you can just pass a second argument to Destroy to tell Unity how long it should wait)

spring tusk
#

IT WORKS ! It finally works. Thanks you all so much

rich adder
swift sedge
rich adder
swift sedge
#

ah

#

so then frostbite became what source is to valve

rich adder
summer stump
#

But... valve actually made source.

stray pelican
#

Hello! I am a beginner with unity and I am running in a bit of an issue.
I called a variable "public int points;" and then tried to increment this variable by 10 every time I called the function pointUp but it keeps resetting my point variable to 0 and I always end up having 10 points no matter what I do. Can someone help me?

#

(I am not in void Update here btw)

wintry quarry
stray pelican
wintry quarry
#

also - why does the function return an int, if it's also modifying a member variable?
It should probably only do one or the other

wintry quarry
# stray pelican

Add Debug.Log to your code to check when it's running and what it's doing

stray pelican
wintry quarry
#
Debug.Log($"Before adding points: {points}");
points = points + 10;
Debug.Log($"After adding points: {points}");```
wintry quarry
#

which class is this on?

short hazel
# stray pelican

Is that script on an object that gets destroyed at some point?

wintry quarry
#

Share all the relevant code in paste sites !code
And explain which components are on which objects.

eternal falconBOT
stray pelican
wintry quarry
#

You want each block in the game to track its own number of points?

#

Because that's what you're doing

short hazel
#

Called it - destroy a block and its own number of points is lost

wintry quarry
short hazel
#

You should keep the point count in an object that does not get destroyed, maybe that's the original point of using return in the method? So you can get the number of points this block gives, and store it in another variable?

stray pelican
#

okayy I think I understand

#

so I should do another script?

wintry quarry
#

You would need a centralized manager that keeps track of score, yes

stray pelican
#

because when the block is destroyed it destroys my points

wintry quarry
#

Just think about it. Should each tetris block have its own "score" variable? That doesn't make much sense.
Same thing with the grid etc

#

these should be part of some central game manager type thing

stray pelican
#

haa okok

#

honestly for everything except the points I followed a tutorial

#

but yeah I get it

#

thx! I'm gonna try that

swift crag
#

when designing your game, it's important to think about who "owns" a concept, as well as how many "owners" you'll have

#

A block might own its own score (maybe you have special golden blocks that give more points)

#

but it should not own the total score

vast ivy
#

why Cant I drag my GameObject parent into the editors GameObject section?

wintry quarry
vast ivy
#

do I have to apply the script to something before I can link them?

wintry quarry
#

You would need to look at the inspector for a GameObject in the scene that you attached the script to

vast ivy
#

ah ok

wintry quarry
vast ivy
#

yea I thought I could just link it before I used it somewhere

swift crag
#

When you click on a script asset, you're inspecting the script itself

#

you can set defaults for when you add new instances of the component

#

i've never really used that

queen adder
cosmic smelt
#

Yo a while ago someone gave me a website to help me with c# can someone help me remember i know nothing

cosmic smelt
# rich adder check the pins

Yo its telling me that i should download an LTS version of unity but i already have normal unity what should i do

swift crag
#

the LTS version is about as close to "normal unity" as it gets

warped ginkgo
cosmic smelt
swift crag
#

no, they won't "stop working"

#

the long term support version is just a major release of Unity that gets patches for a long time

queen adder
swift crag
#

If you have an existing project, use whatever version it uses.

#

If you don't, install the 2022 LTS.

cosmic smelt
warped ginkgo
swift crag
#

The tutorial should tell you this

#

make sure to read it (:

cosmic smelt
#

It does but why cant i do it in normal unity

swift crag
#

because the templates were only made for the 2021 LTS

#

this is also "normal unity"

#

it's just an older version

cosmic smelt
#

And there is 2d platformer microgame on the one i have

dense root
#

Does text have a method similar to button's onClick or should I just use a button and the methods from that for simplicity?

public class ClickExample : MonoBehaviour {
    public Button yourButton;

    void Start () {
        Button btn = yourButton.GetComponent<Button>();
        btn.onClick.AddListener(TaskOnClick);
    }

    void TaskOnClick(){
        Debug.Log ("You have clicked the button!");
    }
}
cosmic smelt
dense root
rocky canyon
#

if u dont have much storage I would..

#

but if u got room just keep both

cosmic smelt
#

Wont it get confusing?

wintry quarry
swift crag
#

if so, you can either:

  • implement IPointerClickHandler handler in your component
  • add an Event Trigger component and set it up
wintry quarry
#

Or just make it a button

#

with an empty image

rocky canyon
dense root
#

Yeah I saw that IPointerClickHandler but it seemed a bit excessive when I could just use a button

swift crag
#

Oh right, you can just add a Button component

#

duh

rocky canyon
wintry quarry
rocky canyon
#

when u make a new project u can choose the version to use it

cosmic smelt
#

Ohh

swift crag
#

just follow the instructions in the tutorial

cosmic smelt
#

I am but there confusing

swift crag
#

they were written to be followed, not to be completely skipped over

dense root
#

Is there a way to make my button background transparent? Other than setting the color to the background, which I want to avoid in case I change things around

rocky canyon
#

u change the Alpha/Opacity to 0

dense root
#

Oh awesome, I forgot about that. Thakn you

rocky canyon
#

the last number/ lower number in the color picker

dense root
#

Found it, thank you so much

stray pelican
# stray pelican Hello! I am a beginner with unity and I am running in a bit of an issue. I calle...

hello it's me again, I made another script to change the number of points but I wanna call it when a block or when a line is detroyed. I tried using "FindObjectOfType<pointManagement>().pointUp(); " in my script that deletes lines but it tells me
"NullReferenceException: Object reference not set to an instance of an object
TetrisBlock.DeleteLine (System.Int32 i) (at Assets/TetrisBlock.cs:83)
TetrisBlock.CheckForLines () (at Assets/TetrisBlock.cs:60)
TetrisBlock.Update () (at Assets/TetrisBlock.cs:45)"

and I have no idea of what it means

summer stump
# cosmic smelt So do i get rid of the one i have and get LTS

You can have multiple editor versions installed at the same time. No need to get rid of any unless you don't plan on ever using that version again.
And you should almost always be using one of the LTS versions unless forced to use an old one by something you need or want to check out the cutting edge changes is brand new versions.

wintry quarry
#

It means you tried to use a reference that wasn't actually pointing at an object

cosmic smelt
dense root
cosmic smelt
wintry quarry
summer stump
rocky canyon
#

good way to break it more and more until its unsalvageable lmao

summer stump
#

Just follow learn until you have the foundation to know a little what you are doing

rocky canyon
#

errors meant to point u directly at the error.. to save time/ trouble/ headaches

wintry quarry
stray pelican
#

point management is a script what do you mean I don't have a instance

#

like it's not connected to anything?

summer stump
stray pelican
rocky canyon
#

you're saying BlueScript.DoSomething();
and the editor is like yo, guy.. I don't know what BlueScript you're talking about.. its either missing or you didn't tell me which one to use

dense root
stray pelican
wintry quarry
rocky canyon
#

if pointManagement isn't on a gameobject in the scene it wont find it..

dense root
#

Well yeah because you're telling the code to find the pointManagment object in the scene

rocky canyon
#

if its a Manager type script or something you can jsut attach it to an Empty GameObject and give it a good name

stray pelican
#

okok I think I understand thx! I thought that it could work if I just used debug

rocky canyon
#

regular monobehaviour scripts that aren't attached to anything in the scene will get completely ignored when u build.

stray pelican
#

god it workkkksss thxxx

dense root
#

Celebrate good times

rocky canyon
#

if u can.. you might want to cache the reference in a variable in Start() or Awake()

#

that way ur not using FindObject every time u run that loop

#

bad for performance

stray pelican
#

I meannn it's a tetris performance should be ok

#

if it works don't touch it

rocky canyon
#
private pointManagement myPointManagementScript;

void Awake(){
myPointManagementScript = FIndObjectOfType...```
#

then u can just call myPointManagementScript.pointUp();

#

you'd already have that reference stored

stray pelican
#

ha

#

ok

#

Imma try

rocky canyon
#

just a good tip for later.. might be fine for a tetris game.. but depending on how many times that looop runs. and especially if its in an update or something

stray pelican
#

yeah I understand

rocky canyon
#

b/c unless its accessed elsewhere theres no need to make it public

#

keep things private unless they have to be made public (like in order to access them from an external script)

stray pelican
#

it's accessed when I update my point no?

stray pelican
rocky canyon
#

well its more like exposure..
if other scripts can access it.. (like when they don't need to)
it could be easy to accidently call a function or rewrite a value u dont mean to..

stray pelican
#

ha okkk

rocky canyon
#

or if its public in the inspector u could risk forgetting to assign it or something

stray pelican
#

okok

stray pelican
#

like pointUp()?

rocky canyon
#

and u can still assign it in the inspector if u'd like
you can make a private variable visible in the script's inspector
by adding [SerializedField] in front of it..
like
[SerializedField] private CharacterController myCC;

#

u could drag it in and assign it in the inspector.. but it wouldn't be able to be accessed outside that class still

rocky canyon
#

just this part

#

;

stray pelican
#

ha

#

oks

rocky canyon
#

and then when u say myPointManagementVariable.pointUp();
its the same as
FindObjectOfType<pointManagement>().pointUp(); (but not really, b/c its already been assigned, ur just accessing that instance of the pointManagement script)

stray pelican
#

I feel like a two years old

slender nymph
#

you need to get your !IDE configured

eternal falconBOT
slender nymph
#

after that you should declare the variable in the class

stray pelican
rocky canyon
#

ur code editor

summer stump
#

What is myPointManagementScript?

Ah, yeah after fixing your ide

summer stump
rocky canyon
summer stump
#

Hint, it is nothing

rocky canyon
#

lol..

dense root
#

Hmm so the way I'm doing this seems bad in the long run but I have two separate scripts, one attached to my enemy and another attached to my button. Both call the camera to switch. How would you handle this?

wintry quarry
#

or rather

dense root
#

Would you attach it to the enemy or the UI? Probably the UI, right?

wintry quarry
#

you should make a function that switches to the battle state

#

in a singleton probably somewhere

#

and both of these pieces of code should call that function

dense root
#

Interesting, I've never used a singleton I'll look into that

rocky canyon
#

FindObjectOfType() is ❌ deprecated in Unity6 anyway 😈

swift crag
#

only because it's been replaced by a version that lets you specify if you care about it being the first object or not

#

well, by two functions

dense root
vast ivy
#

Any clue why Im getting a null reference when I interact with this object with the Item class on it? The interactions are working correctly, it just stopped working when I tried to get the itemName from class Item
item.cs:

using UnityEngine;

public class Item : MonoBehaviour
{
    public string itemName;
    public Sprite icon;
    public int maxStack;
}

Interact function:

    private void Interact()
    {
        Ray ray = playerCamera.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0));
        RaycastHit hit;

        if (canInteract)
        {
            if (Physics.Raycast(ray, out hit, interactRange, interactableLayer | collectableLayer))
            {
                GameObject interactedObject = hit.collider.gameObject;
                string objectName = interactedObject.name;

                if (objectName == "Charging Station")
                {
                    playerStats.ToggleCharging();
                }
                else if (objectName == "Chip Terminal")
                {
                    ToggleChipTerminal();
                }
                else
                {
                    Debug.Log("Interacted with: " + item.itemName);
                }
            }
            else
            {
                Debug.Log("Nothing interactable in range");
            }
        }
    }
swift crag
#

well, what is the actual error?

#

there are plenty of places here that could cause an exception

short hazel
swift crag
#

look at the line number, then verify that everything used on that line isn't null

vast ivy
#

heres the full error message fen: NullReferenceException: Object reference not set to an instance of an object

swift crag
#

okay, and what line is it coming from

short hazel
#

You might want to actually get that script on the object you just hit with the raycast, right? Because you're not doing that right now

swift crag
vast ivy
#

I did it earlier in the script with this line: public Item item;

#

oh wait

swift crag
#

yes, that declares a field that holds an item

short hazel
#

That targets one specific item. Your raycast might be hitting something else entirely

swift crag
#

it doesn't do anything to assign a value to that field!

vast ivy
#

so I need to get the object im hitting, get the item component from it, then I can get the info from it

swift crag
#

Correct.

#

TryGetComponent is useful here.

#
if (!hit.collider.TryGetComponent(out Item item))
  return; // give up and quit early

item.foo = 123;
#

or, in your case

#
if (!hit.collider.TryGetComponent(out item))
  return; // give up and quit early

item.foo = 123;
#

since item already exists

#

The first one declares a new variable.

short hazel
#

That variable should probably be kept local if you're not using it elsewhere

swift crag
#

yes -- that simplifies your class

#

you don't want random cruft floating around

#

(my cat is sitting on me. help)

rocky canyon
# dense root Discussion goes a bit over my head, but thank you for that

it's basically a static instance of a class that you can access from anywhere within the scene b/c there's only (1) version of it.. that way there are no conflicts finding the right instance of it.
https://hastebin.com/share/apewuvelot.csharp <-- basic singleton setup
like here in this TestScript.. you can attach this component/script to a gameobject in teh scene and w/o having to assign any more references you can access it from any other script.. like:
TestScript.Instance.MethodYouCanCallFromAnywhere();

swift crag
#

A singleton is anything that should only ever exist once -- not zero times, not two times

rocky canyon
#

great for things like Score Counters, AudioManagers, GameManagers, etc

swift crag
#

"game controllers" are often singletons

#

I have a set of singletons that only exist in individual levels, and then a set of singletons that exist for the entire life of the game

rocky canyon
#

only way i like em! 😈

dense root
#

Right I get the overall concept

#

Thank you for the explanations

rocky canyon
#

de nada.. i was just pasting the relevant snippet of code from that source i linked.. as u mentioned it was a bit over ur head..

#

that way u can kinda focus on the important part of it.. and work it out

#
  public class Widget : Singleton<Widget>
  {
  }``` my singletons are *tiny* now, I love it ❤️
spiral narwhal
#

OnApplicationQuit() is called before OnDisable() :(
Is there a way to make sure it does OnDisable first

summer stump
#

like disabling the object you want OnDisable called on, or just doing the behaviour manually

spiral narwhal
#

I see, I think i will use OnDisable instead of OnApplicationQuit and change the execution order

eternal needle
spiral narwhal
swift crag
#

this only really matters if you have Domain Reload disabled

#

which only matters in the editor

spiral narwhal
#

Still, it feels more clean to actually do the unsubscriptions.
Btw I solved this using OnDestroy

swift crag
#

one thing I've noticed is that, when the scene is being torn down as the game quits, objects can start comparing equal to null immediately after they get destroyed

#

(rather than this waiting to happen at the end of the frame)

#

I have a singleton class that instantiates a prefab if an instance isn't available

#

it wound up spamming lots and lots of copies of the prefab

rocky canyon
#

the new update makes inline code look soo much more presentable 🙂

spiral narwhal
swift crag
#

I need to go look at that again

#

maybe make a small test project to really figure out what order stuff is happening in

#

OnDisable gets called on everyone before OnDestroy does, iirc, so you can subscribe and unsubscribe in OnEnable and OnDisable instead

zenith cypress
swift crag
#

...but sometimes I really need to stay subscribed at all times, even when the component is disabled

spiral narwhal
#

Oh no, I've solved it now :)

swift crag
#

(e.g. I want to be able to enable the component in response to an event)

spiral narwhal
#
using main.model;
using main.service;
using UnityEngine;

namespace main.mono
{
    public class GameCloser : MonoBehaviour
    {
        private void OnDestroy()
        {
            ServiceManager.Instance?.CloseAll();
            GameSaveManager.Instance?.Close();
        }
    }
}

That was all I needed in my case

wintry quarry
#

🤔 I would think thjat doesn't work

#

Because ? won't detect destroyed objects

spiral narwhal
#

They aren't mono behaviours

wintry quarry
#

Ah

swift crag
#

✨ they are now ✨

#

I wound up writing this

wintry quarry
#

Make them implement IDisposable 😃

swift crag
#
public static bool Safe => _instance != null;
#

this tells me if the instance either doesn't exist at all or got destroyed by unity

#

I have Domain Reload off, so I have to make sure everything unsubscribes from static methods properly. I also try to unsubscribe from everything else so that I'm certain the game will behave properly as I go back and forth between scenes

#

(even outside of the editor, forgetting to unsubscribe from something that lives longer than you is a problem!)

marsh saffron
#

Sorry to bother anyone, but I am struggling trying to figure this out. When I start the game, my player movement doesn't want to function.

moveDirection = cameraObject.forward * inputManager.verticalInput;

this is the line that the error is finding, and im not really understanding why.

marsh saffron
summer stump
# marsh saffron

The null reference is going to be cameraObject or inputManager (or potentially verticalInput, but that is likely a value type, so cannot be null).
Assuming that code is PlayerLocomotion line 31

winter fractal
#

Very very stupid question (probably not coded related), but does someone know why I cant click on the elements of my canvas?

#

I can move the elements changing the transform values, but I dont know what option I touched that I cant move them using the mouse in the editor

north kiln
winter fractal
#

oh thanks man

void seal
#

Getting hit with the classic noob dilemma of not being to use the + operand for type Vector3 and float. What I'm trying to do is add a positive-y offset to my camera which is hard coded to follow the player. The focus.position being that it's centered on the player. I can give more info as needed. Hope this question was clear!

winter fractal
#

sorry again for posting here, didnt found the UX place

void seal
verbal dome
outer coral
#
using UnityEngine;

public class FollowSquirrel : MonoBehaviour
{
    private SquirrelMovement squirrel;
    private RectTransform rectTransform;

    private void Start()
    {
        squirrel = FindObjectOfType<SquirrelMovement>();
        rectTransform = GetComponent<RectTransform>();
    }

    private void Update()
    {
        Vector2 screenPos = Camera.main.WorldToScreenPoint(squirrel.transform.position);

        rectTransform.localPosition = screenPos;
    }
}

im trying to make a UI object follow the screen position of my gameobject, the movement is right it is just weirdly offset and this offset changes when the screen size changes (i.e if i drag the game window to make it bigger/smaller the offset will shift) anyone know why this is occurring? Seems like it would be an easy fix but google is unhelpful on this

void seal
#

Feel like I'm missing something obvious.

#

bleh

outer coral
#

Its readonly you cant modify it like that

#
Vector3 myVec = focus.position;
myVec.y += cameraOffset;
Vector3 targetPoint = myVec;
north kiln
# void seal

You also need to configure your !ide . Errors should be underlined in red

eternal falconBOT
verbal dome
#

Also you should configure your !ide. I dont see error highlighting in the screenshots

eternal falconBOT
void seal
#

Ok. Thought I did configure the other day but might have done it wrong.

#

Sorry and thanks.

wicked osprey
#

So I tried to make a certain custom button change transparency on hover

public class ButtonHighlighter : MonoBehaviour
{
    private void OnMouseOver()
    {
        Debug.Log(gameObject.name + " highlighted");
    }

    private void OnMouseEnter()
    {
        Debug.Log(gameObject.name + " highlighted");
    }
}

But it won't fire, neither on Canvas elements nor game objects.
I mean it's simple, as shown in the Documentation, but won't do...
What am I doing wrong here? (or is it the facts it's 3am here?)

wintry quarry
wicked osprey
#

what?

wintry quarry
#

Use IPointerEnterHandler / IPointerExitHandler

wintry quarry
wicked osprey
#

Yeah, maybe I overread it

wintry quarry
#

It's for objects with colliders

#

Not UI

wicked osprey
#

I really should call it a night XD

wintry quarry
#

Actually first line:

Called every frame while the mouse is over the Collider.

wicked osprey
#

clearly: don't try to read at 3am XD

#

thx

outer coral
# outer coral ```cs using UnityEngine; public class FollowSquirrel : MonoBehaviour { priv...

update on this...

i am printing out the screenPos and it prints the correct coordinates, however for some reason, although I am setting the rectTransform's position exactly to that, it is the wrong values. e.g. screenPos prints 888, 417 and the rectTransform gets set to 1765, 958. I am guessing it has something to do with my canvas setup or something but I am using localPosition so I am a little confused, interesting that it is double (roughly) the printed coords

wintry quarry
outer coral
wintry quarry
#

Yes but it's complicated

outer coral
#

crap

#

is there a workaround

wintry quarry
#

Like you suspected it depends on your canvas settings as well as your canvas scaler

#

Some of this can help

void thicket
#

RectTransformUtility.ScreenPointToLocalPointInRectangle

#

Something like that but it is not so intuitive

wintry quarry
#

My favorite way is to just use Screen Space - Camera canvas

#

and then you can basically just put things at world space positions and it works IIRC

outer coral
#

i think I do have a camera canvas set up

#

if you mean like an orthographic camera ontop of the ui

wintry quarry
#

Like literally:

        rectTransform.position = squirrel.transform.position;``` when you use screen space - camera
wintry quarry
void thicket
#

given that camera is same camera as world camera, yes

outer coral
wintry quarry
outer coral
#

just tried it

wintry quarry
#

And?

outer coral
#
using UnityEngine;

public class FollowSquirrel : MonoBehaviour
{
    private SquirrelMovement squirrel;
    private RectTransform rectTransform;
    private void Start()
    {
        squirrel = FindObjectOfType<SquirrelMovement>();
        rectTransform = GetComponent<RectTransform>();
    }

    private void Update()
    {
        Vector2 screenPos = Camera.main.WorldToScreenPoint(squirrel.transform.position);

        print(screenPos);

        RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, screenPos, Camera.main, out Vector2 newScreenPos);

        rectTransform.localPosition = newScreenPos;
    }
}

its even further off now

wintry quarry
#

that's - not what I said

outer coral
#

oh lol

#

1 sec

#

no way its that easy right

void thicket
#

Sometimes it is

outer coral
#

no does not seem to be working either

#

could it be because of the render camera?

wintry quarry
#

render camera?

outer coral
#

like i have a ui camera on top of the canvas

void thicket
#

ui_cam

wintry quarry
#

oh yes

void thicket
#

So it is not the same cam

wintry quarry
#

assuming that's not your game camera

#

then yes it could be because of that

outer coral
#

it is not

#

ok

#

so is it just not possible to do this then

wintry quarry
#

of course it's possible

void thicket
#

When I'm lazy I just use world space canvas on the character

outer coral
#

last resort maybe

wintry quarry
#

I mean in this case you could do:

Vector3 localPos = gameCamera.transform.InverseTransformPoint(squirrel.transform.position);
Vectot3 worldPos = uiCamera.transform.TransformPoint(localPos);
rectTransform.position = worldPos;```
#

(I think)

outer coral
#

ill try

void thicket
#

*given that both camera has same settings

wintry quarry
#

yeah if their projections/fov/orthographic size etc are different that further messes things up lmao

outer coral
#

well they are lmao

#

i shouldve probably been more specific

#

they r both orthographic just in different spots

void thicket
#

RectTransformUtility is "proper" way to do

wintry quarry
void thicket
#

While verbose

wintry quarry
#

they just need the same orthographic size and projection type

#

But yeah RTU is the robust way to go

outer coral
#

does it matter if one is an overlay?

wintry quarry
#

no

outer coral
#

i see no reason for what you sent to not work then

#

but alas

#

here we are

lavish magnet
#

Object reference error here. But in Start() I set it buttonTExt = GetComponentInChildren<TextMeshProUGUI>();

#

The child of the object with this script on it has a textmeshpro ui component on it?

wintry quarry
cosmic dagger
#

is the object with the script active?

lavish magnet
#

I put it in Debug mode, everything else on the script works

#

It doesnt detect it

lavish magnet
#

Its a button with textmeshporugui under it

cosmic dagger
#

is it the correct component?

wintry quarry
#

those are the two options

lavish magnet
#

Why would strat not run

wintry quarry
#

When you have eliminated the impossible, whatever remains, however improbable, must be the truth
Sherlock Holmes

wintry quarry
#

lots of reasons

lavish magnet
#

If theirs no update does that matter?

wintry quarry
#
  • This is running before Start
  • Your object isn't active
  • The script is disabled
  • The object is a prefab
lavish magnet
#

None of those are true though?

wintry quarry
#

Prove it

#

also

#

show the full stack trace of your error

lavish magnet
#

Wait wrong error oops one sec

wintry quarry
#

yeah looks like the wrong line entirely

lavish magnet
wintry quarry
#

then line 24 won't run at all

cosmic dagger
#

can you post the actual error lines from your script?

wintry quarry
#

this will make line 24 not run at all

lavish magnet
#

I am so sorry i did not realize i tried to use the component before i even used GetComponent

#

It's been a bit

#

Ive got it now

outer coral
#
        Vector2 screenPos = Camera.main.WorldToScreenPoint(squirrel.transform.position);

        RectTransformUtility.ScreenPointToLocalPointInRectangle(rectTransform, screenPos, uiCam, out Vector2 newScreenPos);

        rectTransform.localPosition = newScreenPos;

this is super close, the issue now is that its moving in the correct direction whenever my player is moving, but its just not moving enough? but it starts in the correct position and everything idk whats happening

#

I do have cinemachine so my thought is that is whats making it mess up?

void thicket
#

Thus you'd want your transform's parent

#

To go in the first parameter

outer coral
#

rectTransform.parent as RectTransform

this works? or no

void thicket
#

Well that works, not pretty

#

And remember that your rect transform's position is based on your pivot

outer coral
#

yup that did it

#

love you @void thicket

#

that shouldnt have taken that long but i learned something so ill call it a win

lavish magnet
#

With TextMeshProUGUI, I have multiple menu buttons. And when i hover over them i want the buttons outline width to change to 1, WHy does this change very instance of this buttons outline width?
buttonTExt.outlineWidth = 1;

#

Am i supposed to change something else?

wintry quarry
#

So maybe something else in your code is off

lavish magnet
#

Well even just changing it in the inspectro

wintry quarry
#

changin in the inespector I would expect to affect them all

lavish magnet
#

if i Ctrl D - Duplicate the button, and manually change the width of 1, it does it

wintry quarry
#

because that changes the material

lavish magnet
#

Is their a way to not do that in the inspector?

wintry quarry
#

give them different materials

warm condor
#

Hi guys, I have this issue where a boolean value is set to true based on the current input and the previous input. The problem is that that variable will stay true only for a few frames and it will go back to being false. What I want it for that variable to stay true, even if the condition turns out to be false.Is there a way I can program the boolean variable to wait till it becomes true and once it is true, I can manually set it to false when a condition is met?

wintry quarry
#

at a simple level though:

myBool = myBool || theCondition;```
#

or maybe more understandably if you don't know boolean logic well, just:

if (!myBool) {
  myBool = theCondition;
}```
north merlin
#

Hey guys. I want to snap and object around its local Y axis as shown in the image through code. How would i go about changing the objects forward facing direction while keeping its perspective. (kinda like making it spin on its y axis but without the spinning, i just want to hard set it.)

wintry quarry
north merlin
#

if the object was completely vertical, I could do transform.localRotation...and sets its y value

#

but its not so all 3 values need to be edited.

wintry quarry
#

If you want to rotate the object around its local y axis just do transform.Rotate(0, 90, 0)

north merlin
#

that would maintain its perspective?

wintry quarry
#

idk what you mean by "maintain its perspective"

#

it will rotate the object around its own y axis

north merlin
#

perspective means basically how the object looks to the eye

wintry quarry
#

90 degrees clockwise around it, in this case

summer stump
#

Any rotation would of course change its perspective

wintry quarry
#

so it won't remain the same way

summer stump
#

The fov would not change, but the perspective would, by definition.

#

Even translating tiny bits side to side would change it

north merlin
#

image 1 has a rotation of 90 and image 2 has a rotation of 0 but to my eyes they look the same. I want image 2 through code

wintry quarry
wintry quarry
north merlin
#

no. i just want to change it in game as shown by the images

summer stump
wintry quarry
summer stump
# north merlin yes

Then it will look the same 🤷‍♂️
Perspective is the wrong word for that imo

wintry quarry
#

yeah IDK why you're using the word persective. You just mean you still want it to be tilted over like that I guess

north merlin
#

yes

wintry quarry
#

So, back to my original answer then

#

transform.Rotate(0, degrees, 0)

viral shadow
#

guys im encountering the most absurd issue

#

here let me show yall

north merlin
#

rotate is an addition. I have the final value i want it to be which will constanly change.

wintry quarry
#

Or just compose the tilt and the y axis rotation as quaternions, if you're comfortable with them

north merlin
#

that wont work as the tilt is done on spawn

viral shadow
#

can anyone help with that?

wintry quarry
north merlin
#

the problem will just affect the child object rather than the parent. I have tried this approach before.

wintry quarry
north merlin
#

nvm, ill figure something out

wintry quarry
#

I mean, I've given you multiple working solutions

#

You will come around to something similar

summer stump
#

The only way that wouldn't have worked is if they did something weird with it.
Showing what they tried would have helped in diagnosing that

cosmic dagger
#

what weird stuff we talkin' here? 😉

summer stump
#

I dunno, non-uniform scale on the parent was my first guess

#

But maybe something more.... interesting ? Haha

cosmic dagger
#

ohhh, that's the stuff . . .

wintry quarry
#

or they applied rotations to the wrong objects or used the wrong thing between rotation and localRotation

restive kayak
#

I'm working on a rigidbody player controller, I'm manually setting the velocity of the player through rigidBody.linearVelocity = new Vector3(inputVelocity.x, rigidBody.linearVelocity.y, inputVelocity.z);, and I'm using Debug.Log(new Vector3(rigidBody.linearVelocity.x, 0, rigidBody.linearVelocity.z).magnitude) to read the horizontal velocity of the player. The rigidbody's gravity is enabled and is default (9.81). When the player is on the ground and their movespeed is 10, their horizontal velocity is 9.94114 instead of 10, but when they are in the air, it is 10. I made sure the ground material's dynamic and static friction are 0 as well as it's bounciness and I made sure the rigidbody's drag is 0 but this problem still occurs. Can anyone explain why and how to fix it?

dense root
finite lark
warm condor
#

This is really vague.

wintry quarry
#

and gaining velocity

#

thus fighting against your code

finite lark
#

oh ok

summer stump
# finite lark oh ok

You can use the layer matrix to disable collisions between the sword and ground (and likely walls), or have your code NOT force it into the ground and walls

#

Or just call the jittering purposeful and leave it

wintry quarry
#

I don't see any good reason that sword should be dynamic

#

if it's fully controlled via code

finite lark
summer stump
#

Oh yeah. That is a good point (what praetor said)

dense root
#

When using LineRenderer how do I break the line when the mouse is let go?

private void Update()
{
    if (Input.GetMouseButton(0))
    {
        Vector3 currentPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        
        currentPosition.z = 0;

        Debug.Log("currentPosition " +  currentPosition);
        Debug.Log("InputMousePosition " +  Input.mousePosition);

        if (Vector3.Distance(currentPosition, previousPosition) > minDistance)
        {
            if (previousPosition == transform.position)
            {
                lineRenderer.SetPosition(0, currentPosition);
            }
            
            lineRenderer.positionCount++;
            lineRenderer.SetPosition(lineRenderer.positionCount -1, currentPosition);
            previousPosition = currentPosition;
        }
    }
}
wintry quarry
dense root
#

The line is currently being drawn but when I let go of the mouse it continues to draw

#

1 connects to 2, I know it's hard to see

velvet mango
#

how would i go about getting the name of an GameObject that just triggered a OnTriggerEnter?

wintry quarry
#

Or do you mean when you click again it does that

cosmic dagger
dense root
wintry quarry
#

you would need another line renderer

#

or you would need to make a section of the line between the clicks have 0 width

restive kayak
dense root
rich adder
summer stump
eternal falconBOT
north merlin
#

found a fix. I just subtract the current y rotation from desired rotation and used the product in transform.rotate

summer stump
#

Well, that is certainly one way to approximate just setting it. Glad it works for you!

restive kayak
velvet mango
#

to the three people that responded, imagine im very stupid and dont know how to do them, cause im not sure where to put .name, dont know how to access the GameObject from collision and cannot find how to on the API, and im not sure how to check gameobjects name comparison

rich adder
eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

cosmic dagger
restive kayak
# restive kayak

solved the problem, the capsule collider didn't have a material on it and therefore had friction with the floor

velvet mango
#

i think i figured it out based on @wintry quarry's Solution, thanks

wintry quarry
velvet mango
#

so it would

void seal
#

So with this, hit is the raycast name variable we're checking for? So all raycasts begin with Physics.Raycast? And the out hit specifies the bool we're trying to compare to?

wintry quarry
#

it is a RaycastHit

#

the Raycast function returns a bool

#

which is why you can put it inside the if

#

it also populates that RaycastHit variable in addition to returning a bool

#

it is able to populate it due to the out thing

#

is the raycast name variable we're checking for
This part of your question doesn't make any sense to me

#

what is a "raycast name variable" and what would it mean to "check for" it?

void seal
#

Trying to move over to Unity and C# from Godot. So I'm used to just doing if raycast_named_this.

#

The bool would be in the return and in turn I use that variable.

wintry quarry
#

I don't know how Godot works, and that seems strange to me

#

Yes unity does the same

#

Raycast returns a bool

#

The raycast function fires an imaginary ray into the physics scene according to the parameters you give it. If it hits something, it returns true. If it doesn't hit anything, it returns false

void seal
#

pog

wintry quarry
#
bool hitSomething = Physics.Raycast(...);
if (hitSomething) {
  // do stuff
}```
#

you could write it in this more verbose way if you wish but it's usually more convenient to just do if (Physics.Raycast(...))

#

Gosh I'm loooking at the Godot docs for raycast and they're not very good

zenith cypress
#

Godot's raycasts are overly complicated

void seal
#

Gotcha. Trying to make a specific variable name to reference for complex bs.

wintry quarry
#

Seems like it returns a map/dictionary and the whole thing is just falsey if it hits nothing?

summer stump
#

I do feel spoiled by unity docs pretty often
Especially working with all these pre 1.0 cargos for rust lately, with no description for any api call, just the names

wintry quarry
#

this is what dynamically-typed languages do to a mf

#

everything's just a goddamn shapeless dictionary blob

zenith cypress
#

And if you don't use the raycast node you gotta set up a raycast query through the world, and it's like man let me just fire a ray shakerat

wintry quarry
#

Apprarently all of the Godot C# docs just use var for all variables making it impossible to tell wtf is going on 😦

void seal
#

In Godot you can also just make a raycast Node, define the direction and length, and can drag and drop it into your code as a bool. It's actually easier for me to comprehend but just less powerful which is why I wanted to learn C#.

wintry quarry
#

I don't really know what nodes are tbh. Is that visual scripting stuff?

void seal
#

And that's fair. Even when I was learning Godot I didn't like the sheer amount of vars I'd see on the top of the script. Plain C# makes more sense than Godot C#.

zenith cypress
#

Nodes are their game objects

void thicket
#

Confusing

zenith cypress
#

Well more like if a component became a game object, as each node is a single "type" of a thing. And the inspector shows its inheritence tree.

void thicket
#

You need raycast component?

void seal
#

It's easy to setup but has less fidelity is all.

#

At least from personal experience.

grim tulip
#

How do I learn how code something without just searching up a tutorial every Time I want something done? Ik it takes experience but is there a way to do that without it or just sitting and writing code?

dense root
lavish magnet
wintry quarry
lavish magnet
#

Like in Super mario bros, when the player is hit or gets a power up, It hads a nice animation where the players transparency fades off and on rapidly. How can i recreate this affect? I tried accessing the alpha of the material and it does not work, i am in urp.

wintry quarry
#

Meshrenderer? SpriteRenderer?

lavish magnet
#

3D, Mesh Renderer

wintry quarry
#

You will need to be using a transparent material for transparency to work

lavish magnet
#

Like the shader?

wintry quarry
#

The material

lavish magnet
#

I can set it to Transparent instead of Opaque, But It does not recieve shadows or cast shadows, even though set to On in mesh renderer

wintry quarry
#

If it's opaque it can't be transparent

#

Shadows I guess are a separate concern

lavish magnet
#

Yeah it looks very weird without shadows?

#

what can I do about that 😭 ?

#

Do i just duplicate it without mesh and turn shadows on?>

wintry quarry
#

Probably that. IDK

lavish magnet
#

Lmao

#

I feel like this would be one of the more easier things

topaz fractal
#
{
    private void Start()
    {
        startYScale = transform.localScale.y;
    }


    public CharacterController controller;
    private float movementSpeed = 12f;
    public float walkSpeed;
    public float sprintSpeed;
    public float gravity = -9.81f;

    public float crouchSpeed;
    public float crouchYScale;
    private float startYScale;

    public KeyCode sprintKey = KeyCode.LeftShift;
    public KeyCode crouchKey = KeyCode.LeftControl;

    public float jumpHeight = 3f;
    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;
    Vector3 velocity;
    bool isGrounded;
    

private void StateHandler()
{
    if(isGrounded && Input.GetKey(sprintKey))
    {
        movementSpeed = sprintSpeed; 
    }
    
    else if (isGrounded)
    {
        state = MovementState.walking;
        movementSpeed = walkSpeed;
    }

    else 
    {
        state = MovementState.air; 
    }

    if(Input.GetKey(crouchKey))
    {
        movementSpeed = crouchSpeed;
    }
}

private void Crouch()
{
    if(Input.GetKeyDown(crouchKey))
    {
        transform.localScale = new Vector3(transform.localScale.x,  crouchYScale, transform.localScale.z);
    }
    
    if(Input.GetKeyUp(crouchKey))
    {
        transform.localScale = new Vector3(transform.localScale.x,  startYScale, transform.localScale.z);

    }

} ```
#
    public enum MovementState 
    {
        walking,
        sprinting,
        air
    }

    // Update is called once per frame
    void Update()
    {
        Crouch();
        StateHandler();

         = Vector3.ClampMagnitude(, 1);


        isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

        if(isGrounded && velocity.y < 0)
        {
            velocity.y = -2f;
        }

        float x = Input.GetAxis("Horizontal");
        float z = Input.GetAxis("Vertical");

        Vector3 move = transform.right * x + transform.forward * z;

        controller.Move(move * movementSpeed * Time.deltaTime);

        if(Input.GetButtonDown("Jump") && isGrounded)
        {
            velocity.y = Mathf.Sqrt(jumpHeight * -2f  * gravity);
        }

        velocity.y += gravity * Time.deltaTime;

        controller.Move(velocity * Time.deltaTime);
    }
}
lavish magnet
#

Hello

topaz fractal
#

@wintry quarry

lavish magnet
#

Absolute Business

#

Whats the issue?

topaz fractal
#

when i use any 2 inputs to go diagonally

#

i move faster

wintry quarry
#

Then you can clamp it as per my example

#

Oh wait

#

You do already

#

It's called move

topaz fractal
#

ohhh i get it now

#

it says i cant use it before its declared

#

move = Vector3.ClampMagnitude(move, 1);

#

nvm

#

i just moved it in front

#

sweeet thanks so much

eternal needle
finite lark
#

i got a sword and i made it so whatever direction my mouse is facing the tip of the sword faces and its working all good but now idk how to attach my sword ):

finite lark
#

here lemme get an imag

#

trying to do something like this

wintry quarry
#

I still don't know what you mean when you say "attach my sword"

finite lark
#

well the sword doesnt follow the player it kinda just sits there

wintry quarry
wintry quarry
finite lark
#

yeah i tried that but then if its a child i cant add the rigidbody and get it to work so the sword can affect the player or am i going about this the wrong way lol

wintry quarry
#

and applying drive motor force on the joint to rotate it for example

#

it's not exactly a beginner thing

finite lark
#

ooo

#

ima try and do it (:<

queen adder
#

    public float brakePower = 1; // 1 stops at 1 second, 2 stops at 0.5 seconds
    public float positiveAcceleration = 1;
    void FixedUpdate()
    {
        Truster.gameObject.SetActive(WillMove);
        if(WillMove)
        {
            speed = Mathf.MoveTowards(speed, maxSpeed, Time.fixedDeltaTime * positiveAcceleration);
            rb.velocity = transform.up * speed;
        }
        else
        {
            speed = Mathf.MoveTowards(speed, 0, Time.fixedDeltaTime);
            rb.velocity = transform.up * speed;
        }
    }``` can I get some help with `brakePower` logic
wintry quarry
#

what kind of help are you looking for?
What are you trying to accomplish?

queen adder
#

basically i want it to slow down as the comments say

wintry quarry
#

But wouldn't the time to slow down depend on the current speed?

queen adder
#

move towards not the right thing to use

wintry quarry
#

MoveTowards is fine

#

Is the comment intended to mean from max speed?

queen adder
#

if current speed is 10, it will currently take 10 seconds to halt

wintry quarry
#

Because slowing down from less than max speed should be faster than from max speed right?

wintry quarry
#

10 / 1 is 10

#

10 seconds

queen adder
#

yea so what is supposed to be changed?

wintry quarry
#

You would need to answer my clarifying question first

queen adder
#

current speed

wintry quarry
#

that... doesn't make a lot of sense

queen adder
#

no matter how fst you are, i want it to stop exactly 1 sec

wintry quarry
#

because current speed changes all the time

#

when you're halfway through braking, current speed is half of what you started braking at

#

so you mean.. speed at which you started braking?

#

you'll need to record whatever speed you were going when you started braking then

queen adder
#

yea

wintry quarry
#

then it will be:

speed = Mathf.MoveTowards(speed, 0, Time.fixedDeltaTime * (startedBrakingAtSpeed / brakePower));```
#

but you need to make sure you set startedBrakingAtSpeed properly elsewhere

queen adder
#

then, id have to like edit my willMove

#

to a prop that catches curent speed when falsed

wintry quarry
#

no you just need to set startedBrakingAtSpeed when you start braking

wintry quarry
eternal needle
#

shouldnt lerping be fine there? you'd need to setting the lerp time same way you'd be recording the startedBrakingAtSpeed

wintry quarry
#

sure either way would work

#

both Lerp and MoveTowards result in linear changes over time when used properly

#

Lerp is unlikely to be used properly in this server though 😆

queen adder
#

id probably go with the movetowards with division

#

ig

silent vault
#

go.GetComponent<EventXmlRow>().Init(node, attr);
Regarding this piece of code, is it possible to make the GetComponent type variable ?

wintry quarry
#

can you show an example of what you would like to achieve here?

silent vault
#

Because this class is used as a base class with an init function

#

I'm creating several child classes based on this and I want to init those child classes with their own new init function

wintry quarry
#

wouldn't those child classes just override Init?

silent vault
#

They do

wintry quarry
#

the code that actually calls this wouldn't change then

#

go.GetComponent<EventXmlRow>().Init(node, attr); < this stays the same

silent vault
#

I'm not sure I understand this answer

wintry quarry
#

When you override a function, it replaces the behavior of the parent function

silent vault
#

Currently, this line will call the Init function of the base class

wintry quarry
#

Not if you overrode it

silent vault
#

Yes exactly

#

``using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using UnityEngine;
using UnityEngine.UI;

public class EventXmlRowTrigger : EventXmlRow
{
public Dropdown dd;
private static string[] labels;
private static string[] codes;

public new void Init(XmlNode node, EventsXmlAttribute xmlAttribute)
{
    SetLabel(xmlAttribute);
    this.node = node;
    attribute = xmlAttribute.code;

    if (labels == null)
    {
        labels = GetLabels();
        codes = GetCodes();
    }

    string value = node.String(attribute);

    dd.options = labels.ToDropdownOptions();
    dd.SetValueWithoutNotify(GetIndex(value));
}

public void OnValueChanged(int value)
{
    node.SetAttribute(attribute, codes[value]);
    EventXmlRowEventCode.instance.TriggerMode();
    //Debug.Log(EventEditor.doc.OuterXml);
}

public string[] GetLabels()
{
    List<EventsXmlEnum.Trigger> list = Enum.GetValues(typeof(EventsXmlEnum.Trigger)).Cast<EventsXmlEnum.Trigger>().ToList();
    List<string> values = new();
    foreach (EventsXmlEnum.Trigger value in list)
        values.Add(EventsXmlEnum.TriggerLabel[value]);
    return values.ToArray();
}

public string[] GetCodes()
{
    return Enum.GetNames(typeof(EventsXmlEnum.Trigger)).ToLower();
}

public int GetIndex(string value)
{
    for (int i = 0; i < codes.Length; i++)
        if (codes[i] == value)
            return i;
    return 0;
}

}
``

wintry quarry
#

If you override it properly, it will call Init of the derived class.

silent vault
#

Ups

ivory bobcat
#

When you override a method, it's as though that method has been completely substituted.

wintry quarry
#

that is not how you override things

silent vault
#

Oh

wintry quarry
#

override void Init is how you override it

#

and the base method needs to be virtual or abstract

silent vault
#

Ah... What's the difference with new ?

wintry quarry
silent vault
#

Oh, got it.

wintry quarry
#

it makes a completely unrelated method

silent vault
#

Ok I see. That makes sense. I'll updte my code. Thanks !

#

And the difference between virtual and abstract ?

wintry quarry
#

abstract doesn't have a base implementation

#

and forces the child to implement it

#

virtual has a base implementation and it's optional to override it

silent vault
#

Got it, so in my case, it should be abstract

#

Thanks again

wintry quarry
silent vault
#

Ok thanks! That's exactly what I need.

#

Hm, I've marked both the base class as abstract and the init method as abstract and changed new to override like said but the base init has the following error now "Cannot declare a body because it is marked as abstract"

#

What's a "body" in this case ?

#
    {
        Debug.Log("This needs to be overwritten...");
    }```
wintry quarry
#

public abstract void Init(XmlNode node, EventsXmlAttribute xmlAttribute);

#

An abstract function will only have a signature

#

and leave the implementation to the overriding child class

silent vault
#

Ohhh

#

Ok I understand

#

I removed the body. I didn't know the stuff in { } was the body. but that makes sense.

#

Thanks again 😉

#

Great, it's working as expected now, thanks a lot!

ruby python
#

Mornin' all. Really silly/stupid maths question, but multiplying a number by 1.1 is the same as adding 10% right? lol.

ruby python
#

Okay, thanks. No idea why but my brain just wouldn't wrap itself around that. lol.

dense root
#

How do I change the text of my button?

#
    public Button mButton;
    void Start()
    {
        Button button = mButton.GetComponent<Button>();
        button.onClick.AddListener(TaskOnClick);
    }

    void TaskOnClick()
    {
        mButton.text = ""
    }
languid spire
dense root
#

Why do I want to change the text of my button via script?

languid spire
#

no why the GetComponent

wintry quarry
#

the text is a separate component on a child object

dense root
#

Oh I see

wintry quarry
#

TMP_Text likely of this type

dense root
#

I'm using legacy

wintry quarry
#

Text then

dense root
#

How do I get the child object from mButton?

wintry quarry
wintry quarry
#

public Text myText;

dense root
#
public class HintSystem : MonoBehaviour
{
    public Button mButton;
    public Text mText;
    void Start()
    {
        mButton.onClick.AddListener(TaskOnClick);
    }

    void TaskOnClick()
    {
        mText.text = "a";
    }
}

Fixed it up a bit

languid spire
#

that's fine

#

but why add the listener in the code and not in the inspector of the Button?

void thicket
#

I prefer assigning in code

#

Inspector so messy

languid spire
#

nothing wrong with it but, when it is done incompletely, as in the code above, it exposes a vulnerability

rare basin
#

why is my IDE going crazy

#

it's saying that UI doesnt belong to UnityEngine namespace

cosmic dagger
#

it doesn't recognize the UI namespace . . .

rare basin
#

yea i already know that

#

but why

#

it doesn't recognize text mesh pro aswell

#

and many other things

#

althought its just IDE, no errors in console and can enter playmode/build

void thicket
#

Maybe regenerate project

rare basin
#

i tried that already

cosmic dagger
#

looks like your configuration broke . . .

void thicket
#

Switch to Rider Rider

rare basin
topaz mortar
#
item.EndDrag();```
Does this not work? Item does contain a public method EndDrag
rare basin
#

i tried deleting Library aswell

#

and .cspro jfile

topaz mortar
#

it works in other places:

void thicket
#

Maybe it's not same Item they are looking

rare basin
#

probaly it's trying to use Item class from another asset

topaz mortar
#

ah forgot to add the namespace 🙂

void thicket
#

I think Item is too generic for a class name

flat summit
#

Hey. So when i load a new scene, my main camera gets destroyed (as it should) but then i get null errors when the new scene starts for stuff that uses the main camera.

wintry quarry
#

As in - Camera.main?>

#

If so - you need to make sure the camera in the new scene is properly tagged with the MainCamera tag

flat summit
#

yeah sorry, so i use the main camera for input stuff, getting the reference in start - cam = Camera.Main

flat summit
# wintry quarry See here

it is,

    private void PlayerInput()
    {
        if (!IsOwner) return;
        mousePosition = Input.mousePosition;
        mousePosition = cam.ScreenToWorldPoint(mousePosition);
    }

Heres the exact code btw, and remeber im setting the reference in start.

rare basin
#

prove it

wintry quarry
#

Does the camera exist when Start runs?

#

What error are you seeing exactly?

rare basin
#

show the camera's inspector

wintry quarry
#

You said "null errors" but didn't elaborate

void thicket
#

So you are setting camera in start

flat summit
void thicket
#

Then camera got destroyed

flat summit
#

yes

void thicket
#

It won't pick up new camera automatically

wintry quarry
rare basin
#

you are caching the camera from the old scene i assume

flat summit
rare basin
#

and you are trying to use the old camera

#

on the new scene

wintry quarry
#

You are still referencing the old one

#

one fix here is simply not to cache the reference

flat summit
#

but start is called when a new scene is laoded no? or am i mistaken

wintry quarry
#

i.e. just use Camera.main every time

wintry quarry
#

Start is called only once per object

#

when that object first starts its Updates etc

#

If the object is DDOL, it won't Start again in a new scene

flat summit
#

thanks, does calling Camera.Main every frame have a biger impact than using the cached reference?

wintry quarry
#

slightly

void thicket
#

You can subscribe to SceneManager.sceneLoaded if that is what you need

wintry quarry
#

Most likely not a concern

void thicket
#

Camera.main was horrible at some time

#

But now it is bit better

flat summit
#

can i use something like a " scene loaded " type of deal?

#

ah just saw that message

rare basin
wintry quarry
#

compared with a field access that is slightly slower

rare basin
#

right ,that makes sense

#

thanks

void thicket
#

I still don't like it as it is associated with tag

#

😦

wintry quarry
#

Camera.main is my guilty pleasure.

flat summit
#
public override void OnNetworkSpawn()
{
    base.OnNetworkSpawn();
    NetworkManager.SceneManager.OnLoadComplete += SceneManager_OnLoadComplete;
}

private void SceneManager_OnLoadComplete(ulong clientId, string sceneName, UnityEngine.SceneManagement.LoadSceneMode loadSceneMode)
{
    cam = Camera.main;
}
#

this works, thanks again!

wintry quarry
boreal hare
#

Hello!! Is there a documentation about win32 api (Windows system)?

wintry quarry
boreal hare
boreal hare
languid spire
boreal hare
languid spire
#

and?

boreal hare
# languid spire and?

I saw a game called KinitoPET and it's using win32 (KinitoPET Made with Godot) I want to make it in unity or smth

#

I saw codemmonkey tutorial about Transparent app in unity

languid spire
boreal hare
#

Wait i saw this

languid spire
#

you can do all kinds of stuff. The question is how will you know what, where and how you have screwed something up without at least a basic understanding of the underlying code

void thicket
#

Unity already wraps most of what you need

boreal hare
languid spire
#

I bet what they did in that game is wrap the game in a C++ windows desktop program. That is ceetainly the way I would approach it

boreal hare
languid spire
#

if you want real low level access to the OS, yes

teal viper
#

C++ and C

languid spire
#

I don't think anybody writes windows desktop programs in C anymore, it's been over 20 years since I last wrote one

teal viper
#

It's used a lot for low level stuff. But I was commenting the "windows is written in C++" message

languid spire
#

I took that to mean user written programs not windows internals

#

indeed a lot of windows internals were written in both C and ASM

errant pilot
#

Hey guys i need help, i want an object to go to a point and slow down exponentially until it reaches it, can anyone help?

ivory bobcat
errant pilot
ivory bobcat
#

Move towards the target and have the distance be a factor

errant pilot
ivory bobcat
#

Is there an issue with coordinates? If you're using coordinates of the same space, you'll not have to do any converting.

#

ie world space

errant pilot
#

theyre both children of different objects

ivory bobcat
#

That shouldn't be an issue if you're using their world coordinates (position instead of localPosition)

quasi sparrow
#

hey guys

ivory bobcat
#

What you'd see in the inspector would be their local position.

errant pilot
quasi sparrow
#

hey guys

ivory bobcat
#

Unless you're only needing the x axis

quasi sparrow
#

my charactr player in unity is weird

#

can you help me please my player character is weird

errant pilot
ivory bobcat
quasi sparrow
ivory bobcat
#

!code

eternal falconBOT
quasi sparrow
#

can you help me with this issue

bright violet
#

i want to make an interaction system. Before going to look for tutorials: to show the nearby interactable objects, should i go for an OverlapSphere? or a collider on the player GO? and would it be heavy to call it on fixedupdate?

quasi sparrow
#

hello

bright violet
swift crag
#

that sounds fine

frank zodiac
#

https://hatebin.com/kplbjgrbpy im trying to make a cube go up and down continously between 2 points but all it does is go up to infinity and never come back to its desired spot

halcyon geyser
#

because youre never applying a different position other than it going up

frank zodiac
halcyon geyser
#

wait ur right

frank zodiac
#

okay nvm im just going to set a box collider with a trigger and use that

#

the issue is the value will never EXACTLY match the endposition cuz it has like 100 decimal numbers

halcyon geyser
#

You could use a lerp

frank zodiac
#

people keep telling me to never use lerp

halcyon geyser
#
void Start()
    {
        startTime = Time.time;
        journeyLength = Vector3.Distance(startPoint.position, endPoint.position);
    }

    void Update()
    {
        float distanceCovered = (Time.time - startTime) * speed;
        float fractionOfJourney = Mathf.PingPong(distanceCovered / journeyLength, 1.0f);
        transform.position = Vector3.Lerp(startPoint.position, endPoint.position, fractionOfJourney);
    }
#

basically this acts like a sine wave function

storm pine
frank zodiac
# halcyon geyser You could use a lerp

the lerp isnt working btw```
private void Update()
{
Vector2.Lerp(startingPosition.position, endingPosition.position, Mathf.PingPong(Time.time, 1));
}

bright violet
#

I got these errors the moment i saved my player map asset. They don't go away and don't let me start playmode. Anyone knows how to fix the bug?

storm pine
# frank zodiac i see..

Or you can use LeanTween with the the pingpong loop if you want the animation with a specific ease (https://easings.net/) instead of lineal movement

halcyon geyser
storm pine
worthy veldt
#

why is if(scriptableObjectOne = scriptableObjectTwo) doesnt return error in my IDE nor Unity ? i swear that was not the case before i upgrade from Unity 2021 with VS 2019 to Unity 2022 with VS 2022

#

fucked me up twice this week, why is this happening, where is my error

languid spire
storm pine
# frank zodiac whats leantween?

It's something from the asset store (https://assetstore.unity.com/packages/tools/animation/leantween-3595) but it's so easy to use, with a lot of tutorials and with a documentation. It's so helpful for animation movements and somethings like that. I'm doing my first game and using it is really helping a lot. You can also use .setOnComplete so when the animation is complete you can do a specific thing

Use the LeanTween tool from Dented Pixel on your next project. Find this & more animation tools on the Unity Asset Store.

worthy veldt
languid spire
#

it's not an error, it's just wrong

worthy veldt
#

always has been ?, no red line under text ??

dark hatch
languid spire
#

there is nothing syntactically incorrect in using asignment in an if but it it is almost never what you want to do

storm pine
worthy veldt
#

well then i guess apparently i never made that mistake before, cause in my memory when i made such typo it wont run. good to know

karmic kindle
#

I have a camera script that can rotate view, but when I do that, dragging with the mouse will keep following the original orientation forward and not follow the camera in the new direction it is facing - Vector3 offset = cam.ScreenToViewportPoint(lastPanPosition - newPanPosition); Vector3 move = new Vector3(offset.x * PanSpeed, 0, offset.y * PanSpeed); transform.Translate(move, Space.World);

#

If I set Space.Self instead, it will follow the direction correctly, but I can't find a way to lock the Y axis to stop the "zooming"

storm pine
bright violet
#

can you auto-set a layer mask from a script? Something like how you can auto add another script from a script if required. I'd like to automate this task to prevent me forgetting to set the right layermask

wintry quarry
ivory bobcat
bright violet
languid spire
#

Sure, custom editor

ivory bobcat
bright violet
# ivory bobcat Permanently? What's the situation/use-case? I'm having difficulty understanding ...

I'm making an interaction system, each interactable object is gonna have an Interactable() script with an IInteractable interface, and is gonna have to reside in the "Interactable" LayerMask. It's something i'll have to set manually each time in the editor and i'd like to avoid the chance of me forgetting in the future. I know i could set it in awake() but i'd like to know if there is a better way instead of changing it each time for each object

cosmic dagger
bright violet
#

i mean i could do that yeah. just wanted to know if what i wanted to make was a possibility

cosmic dagger
bright violet
astral falcon
#

As Invader said, just do it by code if you know, that its gonna be that case anyway

bright violet
#

aight

cosmic dagger
#

Not sure what other way you think there is . . .

bright violet
bright violet
cosmic dagger
astral falcon
#

I guess the question has been answered 🙂 So there is no PreSetLayer or something. Just do it by code when you add/create the monobehaviour/object 🙂

bright violet
wanton crater
#

guys ive been getting this error a lot lately ive never got it before yesterday

#

the script is not that complex

astral falcon
bright violet
halcyon geyser
#

Youve probably renamed the script, where it first had a space in the file name

cosmic dagger
wanton crater
#

what do you mean file name and class match

astral falcon
#

If FollowPlayer does not get called FollowPlayer.cs as filename, it wont work

cosmic dagger
wintry quarry
#

The complexity of the script isn't relevant