#šŸ’»ā”ƒcode-beginner

1 messages Ā· Page 135 of 1

swift crag
#

A frame is completed when the entire Update loop finishes (followed by animation, LateUpdate, ...)

#

one of these objects was instantiated and one was in the scene from the start

dusky oriole
#

Wait, really?

swift crag
#

I incorrectly thought that Start ran on the same frame as Awake for in-scene objects

swift crag
#

That would be nightmarish

#

this is also why the game freezes if you get into an infinite loop

dusky oriole
#

So it's all just one single callstack, no syncing of various parallel operations?

gaunt ice
#

unity is single threaded

swift crag
#

well, if you write code that can run on multiple threads, then you can have work in parallel

#

see the Jobs system for an example

#

But the Update loop is single-threaded.

dusky oriole
#

Then Instantiate has to nclude a call to Awake inside of it no?

north kiln
#

Yes, it does

swift crag
#

Correct. Awake is executed.

#

(assuming the game object is activated)

#

Start doesn't run "at the same time" (and neither does Awake, or anything else)

dusky oriole
#

Shame Unity is open source...

#

isn't*

swift crag
#

Awake is run as part of instantiation, or immediately after activation of the game object for the first time.

#

and Start executes one frame later, at some point before Update is called

dusky oriole
#

Well this puts a lot of things in order. Thanks

swift crag
#

It's really helpful to have a strong grasp of the order things happen in

#

I'd suggest making a few scripts and watching how they run

#

this is what I wrote to double check

#
using UnityEngine;

public class Test : MonoBehaviour
{
    void Awake()
    {
        Debug.Log("Awake: " + Time.frameCount);
    }
    void Start()
    {
        Debug.Log("Start: " + Time.frameCount);
    }
    void Update()
    {
        Debug.Log("Update: " + Time.frameCount);
        Destroy(this);
    }
}
plush cave
#

anyone know what return method should be used on an enumerator if you want it to stop looping once it reaches a specific condition?

gaunt ice
#

yield break;

ivory bobcat
#

Would break the coroutine. To break a loop, use regular break.

plush cave
#

yea the issue is that its not looping its just moving on to the next condition?

ivory bobcat
#

So it's looping or not looping? Maybe provide some actual context.

swift crag
#

yield return produces a value

#

the enumerator will stop until it's asked for a new value

#

If you want to stop looping, then...stop looping

#

change the condition in your while/for/do-while loop

plush cave
#

right i want it loob but until it reaches a specific condition

ivory bobcat
#

Show us what you've tried

swift crag
#

then use that condition to control the loop...?

#

yes, please show us what you're doing

plush cave
#

!code

eternal falconBOT
plush cave
swift crag
#

That looks reasonable to me.

#

Although lines 14-16 sems kind of weird to me

#

Is _decreaseMeter a reference to the Coroutine produced when you started the DecreaseTransformMeter coroutine?

ivory bobcat
#

Maybe decrease speed is zero if you aren't able to escape the first loop

swift crag
#

the entire script would be helpful here

plush cave
plush cave
ivory bobcat
#

Where's the actual error/unwanted behavior?

plush cave
#

the if statement isn't being valued

ivory bobcat
#

Try logging the value

#

I'm guessing you aren't ever able to leave the loop at this point

plush cave
ivory bobcat
#

Log the normalize value in the loop

#

It's the exit condition for the loop. If it doesn't decrease, you'll never escape the loop.

plush cave
#

which value exactly

swift crag
#

GetTransformMeterNormalized()

#

that's from another script, so we don't know what it's doing

ivory bobcat
#

transformMeter.GetTransformMeterNormalized()

plush cave
#

public float GetTransformMeterNormalized()
{
return transformMeter / maxTransformMeter;
}

ivory bobcat
#

What did the value print?

swift crag
#

logging the value in the while loop will also reveal if the code is even running in the first place

ivory bobcat
#

Dude had a log in there before but it wasn't printing anything important

ivory bobcat
#

By logging the value?

queen adder
queen adder
#

just a simple script to catch input 😁

ivory bobcat
#

Is the Any Direction Down function intended to be processed on every call?

plush cave
#

its logging the values properly its counting down as it should

ivory bobcat
#

Even if no keys are pressed

queen adder
#

quite yea

#

can that be optimized?

ivory bobcat
ivory bobcat
queen adder
#

yea, it's catching input, it have to go alltime

#

should I do an anykey?

plush cave
ivory bobcat
#

Show the logs (an image of the console tab)

#

You said it's decreasing, this implies it's going to zero

plush cave
#

it is decreasing from 100 then just rubberbanding at 0.0004, 0.0007 and so on

autumn sedge
#

Hello I am a beginner Unity developer and I have run into this basic problem. I have created a collectible "Gems" entity and it does not want got get in front of the background. I've tried to change the z axis but the gem is still behind of the background. If anyone can help me I would be very grateful. Thx

ivory bobcat
#

So figure out why it's not properly decreasing.

gaunt ice
#

not code question
google sorting layer and sorting order

ivory bobcat
#

Either the decrease function is broken or the value you're calling it with is decreasing and never exceeding what's remaining.

gaunt ice
#

priority: layer>order>z-value

autumn sedge
#

Ok thanks

uncut bay
#

anyone know why I can't drag a prefab onto the scene in 2d unity?

buoyant knot
#

you should be able to. are you dragging a prefab file from your project tab?

uncut bay
#

this is what i'm tryna add

#

it's in the tab at the bottom

#

project tab

buoyant knot
#

that is not a prefab?

uncut bay
#

it's not?

#

here's the inspector

buoyant knot
#

that is a texture

uncut bay
#

oh

plush cave
gaunt ice
#

it is texture not prefab, prefab is gameobject in disk

buoyant knot
#

a texture is a picture

uncut bay
#

how can I make it into a gameobject?

#

I downloaded it online

buoyant knot
#

a gameobject is an entity with components on it in the scene

uncut bay
#

I did the same with another image and it worked that time

buoyant knot
#

one of those components can display a texture

uncut bay
#

oh wait

#

I was trying to drag it into the "game" tab šŸ¤¦ā€ā™‚ļø

#

I switched to the scene tab and then it workd

#

does that mean anything?

buoyant knot
#

no

uncut bay
#

I thought you couldnt drag textures

buoyant knot
#

make an empty gameobject. give it a spriterenderer component. give the spriterenderer the texture

#

idk what you are doing right now tbh

#

but that heart is a texture, not a prefab

uncut bay
#

that's pretty cool, I dragged the texture into the scene and it did the empty gameobject thing automatically

buoyant knot
#

you should avoid doing that outside of defining a prefab, because if you edit those settings, you can’t copy paste it everywhere

uncut bay
#

I should avoid dragging the texture itself?

buoyant knot
#

like if you changed the sorting layer to Layer1, and then dragged another heart texture into the scene, it would automatically make a gameobject with a heart texture on the Default layer

buoyant knot
uncut bay
#

oh alright

#

thanks

buoyant knot
#

Default sprite layer is almost always wrong whenever you build a real game, because you will use multiple layers for sprites

uncut bay
#

yeah that makes sense

#

so from now on, I need to create an empty gameobject

buoyant knot
#

you would need to make a prefab

uncut bay
#

and drag the texture on the gameobject?

buoyant knot
#

well, making a prefab means you make your gameobject with all the components it needs, with all the settings it needs

wintry quarry
buoyant knot
#

like, that heart gameobject is totally useless, as you can’t collider with it, it has no script, it is not in UI, etc

wintry quarry
#

The proper way to do this is:
GameObject -> UI -> IMage
Then set the sprite to that heart. @uncut bay

buoyant knot
#

yes

wintry quarry
#

If it's not in the hierarchy then it doesn't exist in the game

uncut bay
wintry quarry
#

Do you mean it's not in the hierarchy at runtime? Or just in that particular scene at edit time?

buoyant knot
#

if your singleton is a monobehaviour, it needs to be DontDestroyOnLoad if you want that instance to continue to exist between scenes

wintry quarry
buoyant knot
#

or at least you’ll need recttransform

uncut bay
#

alright thx

wintry quarry
#

I have no idea what "I'm just trying to understand which scene at i am." means tbh

uncut bay
#

so I create empty gameobject, then after that what

wintry quarry
swift crag
uncut bay
#

but you just said 3 words

#

gameobject -> ui -> image

swift crag
wintry quarry
#

GameObject -> UI -> Image

swift crag
uncut bay
#

ooooh

#

alright mb

buoyant knot
#

singleton can be a monobehaviour on DontDestroyOnLoad, or just a POCO. and then it will exist between scenes

#

@uncut bay prefab requires you to drag a gameobject from the scene into a project folder

#

this saves the gameobject as a file… a file for a pre-fabricated gameobject

swift crag
#

if a scene isn't loaded, the objects in it will not exist

#

You can definitely use this to detect whether a scene is loaded.

#

If you have a component that's only in one scene, and it stores itself in a static field like this...

#
void Awake() {
  instance = this;
}
stuck mango
#

Hey, what is the best way for a game object lying on another moving game object to move together with it? I tried to parent the first game object with a rigidbody component to the moving game object, but then many weird things happen.

swift crag
#

then instance will be either null (if the object has never woken up) or it will equal null (if the scene has been unloaded, destroying the object)

wintry quarry
buoyant knot
swift crag
#

It's a singleton in my book!

buoyant knot
#

it’s not tho? you could make 10 of them, and nothing would stop you

#

not singleton

stuck mango
swift crag
#

a component that you only ever have one instance of in a single scene in your whole game functions as a singleton.

#

we could argue semantics all day here

wintry quarry
buoyant knot
#

i don’t think it’s semantics. a singleton would need to at least check that the instance isn’t already defined so that it can be single

swift crag
#

however I am not writing an Enterprise Grade Framework here. i am making actual software that does useful work

#

i find a lot of the OOP jargon to be unnecessary

swift crag
#

in this case, I'm making a promise that I won't create two instances by accident

#

i could enforce that through code, but i don't think it's necessary here

#

i'm just slapping a component somewhere in the main menu scene

#

if this component could exist in many scenes, or could exist multiple times, sure, i'd need a different design

buoyant knot
swift crag
#

this is wrong for Sphynx's use-case

#

the object must die when the main menu unloads

buoyant knot
#

singleton. ton that is single. only one

swift crag
buoyant knot
#

it is right for his use case?

#

the whole point of a singleton is to know you are working with the one instance that has all the information of every time you used it

swift crag
#

this is the design goal

buoyant knot
#

if you just blanket let Awake() instance = this; then whenever its called twice, it will overwrite your old information

swift crag
#

I perfectly understand how this could malfunction.

#

I am pointing out that it doesn't matter.

#

You are fixated on the academic definition of the singleton pattern and it's not helping.

#

by the way, if you just want to know if a certain scene is active, you could ask the SceneManager class

buoyant knot
#

it’s not about the academic definition. it’s about the practical use case of calling GetInstance(), and putting in safeguards so it can work properly in multiple scenes

swift crag
#
SceneManager.GetActiveScene().name
swift crag
#

It's true that this violates the mathematical definition of a singleton (a set with one element). I guess we could call it something else.

stuck mango
swift crag
#

But it's close enough for me to understand the design intent.

buoyant knot
#

mine looks like this

#

without the russian

#

or netherlandish

swift crag
#

note that this will create a new object and stick the singleton component onto it if it doesn't exist or has been destroyed

buoyant knot
#

btw, if you are putting that in a monobehaviour class, i recommend putting a line for OnApplicationQuitting

swift crag
#

so I'm unclear about what you mean here now.

buoyant knot
#

private bool _applicationQuitting = false;
pricate void OnApplicationQuit() => applicationQuitting = true;
in getter: if (applicationQuitting) return null;

#

because it protects against several infinite loops when you close an application

#

and it looks like it closed well, but it actually crashed from a stack overflow as you closed

#

i just bring it up because i had those infinite loops happen to me

stuck mango
#

Is there a way to make these cubes interfere with each other better? You can see that when the second layer of them forms they stop moving.

swift crag
buoyant knot
swift crag
#

oh yeah, that'd cause infinite loops if you actually instantiated the object when it can't be found

#

instead of searching for one in the scene

buoyant knot
#

yeah, it keeps making one every time you try to unsubscribe, then breaking it

swift crag
#

I got around that by just returning the existing reference if searching for an object with the right type failed

buoyant knot
#

i check if singleton is null in OnDestroy

swift crag
#

the destroyed object now looks like null, but it's a perfectly valid object as long as you don't need any Unity methods

buoyant knot
#

i also always store a local ref to singleton in awake for classes that use them

swift crag
buoyant knot
#

you normally need to access singletons repeatedly in OnEnable/OnDisable for sub/unsubscription anyway, so the small memory cost pays for slightly faster sub/unsub calls

#

i’m a big fan of premade Singleton<T> : MonoBehvaiour. it makes a lot of this overhead and crap quick and easy

swift crag
#

yeah, it's a very convenient pattern

stuck mango
toxic latch
#

I'm watching a Tarodev video about object references between scripts, etc., and in his example he creates a class called UnitManager (derived from MonoBehaviour but I don't think that's relevant here). He then enters 'private Unit _spawnedObj'.

#

Is Unit a custom varriable type in this example?

swift crag
#

He must have declared a Unit class somewhere else.

buoyant knot
#

yes

toxic latch
#

Alas, I do see the script on the left called Unit, the existence of which is implied I suppose. Thanks.

languid spire
#

do you not see the Unit.cs there?

swift crag
#

not until now!

stuck mango
buoyant knot
toxic latch
# buoyant knot

Yep, saw it as soon as I pasted the screenshot as mentioned. Thanks.

gaunt ice
#
foreach(var item_all in item){ loop1
    foreach(var obj in placement_obj){ loop2
        foreach(var items_UI in items_UI_look){loop3
            if(item_all.placement_ == obj.name){<--this if only use the variable in loop1 and 2
                Debug.Log("no nested foreach pls");
                //Instantiate()
            }  
        }  
    }        
}
```also learn how to use dictionary
wintry quarry
toxic latch
#

Is MonoBehaviour utilized exclusively for components? Is it ever necessary for a script which will not be attached to a game object?

wintry quarry
#

if you're not making a component, it makes no sense to use it.

languid spire
frozen surge
#

Hello what causing of this one an error

wintry quarry
frozen surge
stuck mango
tired pebble
#
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <div class="dropdown">
        <button class="dropbtn">Menü</button>
        <div class="dropdown-content">
    <a href="https://www.google.de%22%3Egoogle/</a>
    <a href="https://www.cvo-bonn.de%22%3Ecvo/</a>
    <a href="https://www.youtube.com%22%3Eyoutube/</a>
    
<title>Solar Stecko</title>
<meta name="author" content="g.kutz">
<meta name="editor" content="html-editor phase 5">
    <head>
        <link rel="Stylesheet" href="style.css">
    </head>
<body background="Images/rasp.jpg">
    <h1 align="center" ><b><font color="#ffd700">Computer Tutorials</font><br clear="all"</b></h1>
        <p></p>
        <p></p>
        <p></p>
            <table width="100%" border="0" cellpadding="0" cellspacing="2">
              <tr>
               <td align="center" ><font face="Arial"</font><b><font color="#00fa9a"><font size="+1">Eine Mini Solarsteckdose zum mitnehmen</font></td>
               <td align="right" ><img src="Images/Solar.jpg" alt="" border="0" width="474" height="315">  </td>
              </tr>
             </table>
             <table border="1" >
             <a href="unterordner/tutorials.html"><p style="text-align:right;">Tutorials</p></a>
    </table>
</body>

</html>
#

I have this html code and when I click on the menu button this happens

#

Why does the picture get shown in the menu?

frozen surge
#

What am i gonna for the "Easy, Normal, Hard" toggles so it can be default to only Easy when it gets cancel it

tired pebble
#

Oh wrong dc my bad

obsidian needle
#

https://hastebin.com/share/uzicareqoj.cpp

how could I add some sort of delay to this, so it requires a double click ? the selection and confirmation both output together with one click.

timber tide
#

probably can just use a few flags

#

once it's down you need to then check if it's back up then down again

wintry quarry
timber tide
#

I think the new input system has some tracking for double clicking

wintry quarry
#

you need states like:

  • idle (listening for first click)
  • listening for second click (either stops after a certain amount of time or the second click comes in time)
swift crag
#

or you can just remember the time you last saw a click

#

and if a click comes soon enough after the first click, you consider that a double click

swift crag
#

"when it gets cancel it"

frozen surge
#

instead of saving the option of the difficulty

fluid remnant
#

anyone know how I can achieve this same mechanic ?

#

I'm thinking this some sort of mesh cutting

#

but how to only allow player to only move on edges after too is confusing

timber tide
#

my crappy solution is to add a position per pixel you cover and add a pointer to and from for each inside of a container

#

doubly linked list

#

probably better solution -> raycasts

fluid remnant
timber tide
#

basically im establishing a route for which the cursor is attached to

wintry quarry
timber tide
#

and then lerping between the positions

wintry quarry
#

either way I think some kind of stencil shader shenanigans are in order

fluid remnant
#

Ohh I think see what you mean, I'm googling these

fluid remnant
timber tide
#

stencils seem like a solution, but im not too sure about getting the hard edges

fluid remnant
#

also the butterfly "enemy" only moves within the unrevealed space which offers another challanage

timber tide
#

well, if you can figure out the current problem then that shouldn't be hard

fluid remnant
timber tide
#

because you're just trying to figure out how to get the inverse zone to cull / mask

#

mesh cutting could also work, but they means you need a lot of verts probably

#

which is why masking is probably more ideal in this scenario, though making a new quad with new verts is a solution too

fluid remnant
#

yeah that might be expensive right? the only positive I see that AI wouldn't be as hard if its only a mesh

#

surprising I cannot find a modern version of this type of gameplay

gilded pumice
#

how much of game creation in coding is setting objects to active and inactive to achieve what you want? I've noticed my list of game objects that I turn on and off with conditional code is a bit long and I'm wondering if it's a trap to get used to dealing with programming this way in Unity. For example, making an empty object with a sound on it that activates and disables when an condition is met- is this a path that will get me into trouble from a resource performance spot later on? and if so what is the best way to combat leaning on something I know in exchange for struggling for hours to do it a different way? I know this question isn't super technical but it's been on my mind as I've acquired more understanding of code writing

timber tide
#

a lot

#

research some object pooling

polar acorn
gilded pumice
#

ok thank you. and Mao I already have it on my list of do does!

crystal fiber
#

In the line:
refresh = false; GameObject item_instance = Instantiate(items_UI, obj.transform.position, obj.transform.rotation); item_instance.transform.SetParent(obj.transform);

I dont get all itemList instantiated, i only get the first one. Can someone explain and help?

`{
public GameObject inv_panel;

public List<items> item = new List<items>();
public GameObject[] placement_obj;
public GameObject[] items_UI_look;
bool has_open;
bool refresh = true;

void Update()
{
    if(Input.GetKeyDown(KeyCode.Tab))
    {
        if(has_open)
        {
            has_open = false;
            inv_panel.SetActive(false);
        }
        else
        {
            has_open = true;
            inv_panel.SetActive(true);
        }
    }
    foreach(var item_all in item)
    {   
        foreach(var obj in placement_obj)
        {
            foreach(var items_UI in items_UI_look)
            {
                if(item_all.placement_ == obj.name && item_all.item_name == items_UI.name && refresh == true) 
                {
                    refresh = false;
                    GameObject item_instance = Instantiate(items_UI, obj.transform.position, obj.transform.rotation);
                    item_instance.transform.SetParent(obj.transform);
                }  
            }  
        }        
    }
}

}
[System.Serializable]
public class items
{
public string item_name;
public string placement_;

public items(string item_name, string placement_)
{
    this.item_name = item_name;
    this.placement_ = placement_;
}

}`

#

tell me if you want more details

amber spruce
#

real quick for some reason i cant seem to remember to check if smth equals smth is it 1 or 2 equal signs???

languid spire
crystal fiber
languid spire
#

then how do you expect a sensible answer if you knowingly post crap code?

cosmic quail
amber spruce
#

thanks

crystal fiber
#

il organize it when its finalize

polar acorn
crystal fiber
polar acorn
#

Oh is the bot not working?

eternal needle
queen adder
#

wsp

polar acorn
queen adder
#

I need help about 2 things

polar acorn
queen adder
cosmic quail
queen adder
#

oh?

#

What exactly is that if you dont mind me asking

cosmic quail
queen adder
#

ohh

#

Wall Street Post haha

amber spruce
#

how can i check if the controller is inputting with the new input system because i made a virtual mouse but only want it to be on if the person is using a controller

cosmic quail
languid spire
#

you've never heard of the Wall Street Post? The worlds second premier financial newspaper

queen adder
#

why is the word any ways blocked?

queen adder
languid spire
#

dark days for the human race and getting darker by the day

queen adder
#

welp

#

may I ask a dumb question

#

or two

languid spire
#

of course

queen adder
#

How exactly do I put the level I downloaded from the unity marketplace thingy into a game/project?

languid spire
#

Package Manager

queen adder
#

can't find anything in youtube

queen adder
#

I open it on there

#

but than

#

I have no idea whats happening

#

I can send a sreenshot, second

languid spire
#

write
in
full
sentences
please

queen adder
#

Alright sorry

languid spire
#

that aint a screenshot and I dont watch videos

queen adder
#

Oh it sent wierd I dont know why but, I do the task manager I import it and than im just stuck on what to do.

languid spire
#

so post a screenshot of your unity window

fickle plume
#

@queen adder This is a code channel, use#šŸ’»ā”ƒunity-talk for general questions. If this is about third party asset you should contact creator instead. And use mp4 containers with supported codec to illustrate

queen adder
fickle plume
#

If it's a basic question about loading assets you should start with Unity Learn really

#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

queen adder
#

Thats nice, thanks!

rich ember
#

Can someone tell me why the Mathf.Clamp causes the camera to jerk to 65 rotation when it hits -5 rotation? I have tried commenting out the clamp and just using newHeadRotation and it works find except for the fact it doesn't clamp it haha. but what am I doing wrong here?

eternal falconBOT
wintry quarry
#

don't use screenshots

#

also your problem is because you're using transform.eulerAngles for your logic - almost always a mistake

polar acorn
wintry quarry
dark hatch
#

for 2d movement: is using velocity better or vector2.movetowards? Velocity has the advantage of no jitter when trying to go into a wall

rich ember
#

but then how do I change rotation? transform.rotation?

wintry quarry
#

Rotate or rotation on the player body for yaw

rich ember
#

hm. ok

#

thank you both digiholic and Praetor

wintry quarry
#

Are you thinking of MovePosition on Rigidbody2D?

dark hatch
wintry quarry
#

use velocity or add forces if you want proper collision

#

MovePosition is intended more for something like a kinematic moving platform.

dark hatch
#

docs on moveposition does say it produces colliders and triggers

#

Because this feature allows a rigidbody to be moved rapidly to the specified position through the world, any colliders attached to the rigidbody will react as expected i.e. "they will produce collisions and/or triggers."

wintry quarry
rich adder
wintry quarry
#

It will not actually cause your moving body to collide properly

dark hatch
#

okay, so velocity does seem better since i do want collisions in my case

buoyant knot
#

collisions in unity are simple bits of information corresponding to an event of two colliders being in contact.
this is not the same as the two colliders applying force to each other during simulation

dark hatch
#

i do have a problem with moving with velocity though: following your general tutorial for player movement just sets velocity to xinput * speed, yinput * speed. Now, if i use addForce for something like a dash effect, it will essentially be ignored because in the next frame, velocity will be again set to a specific value. Now, do i go around this with booleans, or is there a cleaner method? (added context, i am on a 2d project)

rich adder
#

simple state machine maybe ?

dark hatch
lone finch
#

how would you make this event only occur when the hitbox collides at the bottom?

rocky canyon
#

you can use normals

lone finch
#

what are normals?

rocky canyon
#
buoyant knot
rocky canyon
#

its the facing direction of a surface

buoyant knot
#

contact normals from a collision are good and efficient, as long as the thing you are hitting doesn’t have a shape that allows multiple contacts with different normals

#

if you contact with a tilemap, and are touching ground and wall at same time, you will get multiple contact normals

#

it depends on what you want to check

rocky canyon
#

yup, i was guessing it was a simple collider hence the Collision2D

#

but yea, might get a lil difficult for odd shapes

buoyant knot
#

tilemaps

rocky canyon
buoyant knot
#

if you want to see if ANY sort of contact is with floor, and the collider could have some other part like a wall or ceiling at the same time, THEN: use collision2D.GetContacts, and look through the contact normals

rocky canyon
#

so each blue line is the normal for the corresponding face..

buoyant knot
#

if you want to see if (between 2 colliders), give me a direction that will solely count as up/down/left/right regardless of multiple contacts, use Collider2D.Distance

rocky canyon
#

could use multiple colliders too

#

if the math gets too savy for ya

#

wouldn't be as accurate but could probably use it in some cases

buoyant knot
#

like if mario collides with goomba, and you need to know: is this a side collision (mario dies) or a stomping collision (goomba dies), use Collider2D.Distance

#

if you need to know if mario is grounded while touching a tilemap of ground tiles, you need to go use Collision2D.GetContacts()

lone finch
#

i kinda get it

#

thx

buoyant knot
#

sure

#

going through contact normals, if mario is touching floor and ceiling and wall all at once, you will see separate ContactPoint2D, and those contact points will have normals for up, down, and left in different contacts. for example

gentle moat
#

anyone know how to use A*? my enemy finds a path to the player, but dosent move

lone finch
#

im still pretty new to unity

timber tide
#

also new to c# it seems

#

i'd suggest working on some tutorials on the language first

lone finch
#

i just do not really know the unity methods

#

all that well

uncut bay
#

Hi, I have a script attached to my player (2d platformer) and I want to reference the sprite renderer of another gameObject. I wrote the following code:

private SpriteRenderer Heart1; 
private SpriteRenderer Heart2;
private SpriteRenderer Heart3;
void Start()
    {
        Heart1 = GameObject.Find("Heart1").GetComponent<SpriteRenderer>;
        Heart2 = GameObject.Find("Heart2").GetComponent<SpriteRenderer>;
        Heart3 = GameObject.Find("Heart3").GetComponent<SpriteRenderer>; 
    }```
lapis jungle
#

šŸŽ® Play my Steam game! https://cmonkey.co/dinkyguardians
ā¤ļø Watch my FREE Complete Courses https://www.youtube.com/watch?v=oZCbmB6opxY
šŸŒ Get my Complete Courses! āœ… https://unitycodemonkey.com/courses
šŸ‘ Learn to make awesome games step-by-step from start to finish.
šŸŽ® Get my Steam Games https://unitycodemonkey.com/gamebundle

Getting started with U...

ā–¶ Play video
uncut bay
#

with the errors saying Cannot convert method group 'GetComponent' to non-delegate type 'SpriteRenderer'. Did you intend to invoke the method?

#

what can I do instead to access the spriterenderer of another gameObject

ruby python
#

You missed () at the end. (I think. lol.)

uncut bay
#

šŸ¤¦ā€ā™‚ļø

#

yep that's it

ruby python
#

GetComponent<SpriteRenderer>();

uncut bay
#

thanks

#

šŸ˜…

ruby python
#

np šŸ™‚

#

Done it many times myself tbh. lol.

uncut bay
#

The small mistakes are the most frustrating šŸ˜”

gentle moat
timber tide
# lone finch i have coded a bit in c#

always refer to the documentation on what properties you're handling as here you've got a Collision2D so you should be checking what's available to use from that. As for static methods, it's not likely to run into them except a very few cases.

lone finch
#

how did i mess this up? do i need to offset it?

#

camera is supposed to follow character

twin bolt
#

In my game the player falls really slow. Could this code be why? ``` float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");

        Vector3 forward = playerCamera.transform.forward;
        Vector3 right = playerCamera.transform.right;
        forward.y = 0f;
        right.y = 0f;  
        forward.Normalize();
        right.Normalize();

        Vector3 desiredMoveDirection = forward * verticalInput + right * horizontalInput;

        rb.velocity = desiredMoveDirection * playerSpeed;```
frosty hound
#

According to this snippet, your player shouldn't be falling at all

twin bolt
#

oh ok

frosty hound
#

Also, if you're snapping the camera to the position of the goblinSprite, it will be on the sprite. You of course need to offset the (likely) z position to be what the camera's z-position is.

safe root
#

How can i change this so I don't need to put really high numbers. Cause whenever i'm close to object it throws me forward really fast. Yet when i'm far it doesn't do it.

Vector3 playerPosition = transform.position;
        Vector3 grapplePosition = lastRaycastHit.point;

        // Calculate the distance between the player and the object
        float distance = Vector3.Distance(playerPosition, grapplePosition);

        // Calculate the force based on the distance (you can adjust this formula)
        Debug.Log("Got stuck at the math");
        float adjustedForce = basePush / distance;
        

        // Get the direction from the player to the object
        Vector3 grappleDirection = (grapplePosition - playerPosition).normalized;

        // Apply the force to the Rigidbody
        rigidBody.AddForce(grappleDirection * adjustedForce, ForceMode.VelocityChange);
lone finch
#

how would that be separated?

frosty hound
#

Make a new Vector3 that uses the x and y position of the sprite, but the camera's own z.

lone finch
frosty hound
#

You're only providing x and y to a Vector3, add the z as well.

short hazel
rocky canyon
amber nimbus
#

I have multiple triggers on a GameObject - hurtboxes is using tags a good way of checking what trigger was hit? (this check could happen up to 4x a second)

swift crag
#

I prefer using components.

#

Tags work, and may be slightly more performant, but I've never liked working with them

#

You probably want to attach some extra data to each hurtbox anyway

#

e.g. how good it is (you might put hurtboxes that take less damage on some parts of the character)

safe root
swift crag
#
if (collider.TryGetComponent(out Hurtbox hurtbox)) {
  // ...
}
#

Alternatively!

short hazel
swift crag
#
void OnTriggerEnter(Collider other) {
  if (!other.TryGetComponent(out Hurtbox hurtbox))
    return;
  hurtbox.Hurt();
}
safe root
swift crag
#

if TryGetComponent fails, it'll return immediately

uncut bay
#

if I used gameObject.Destroy will the gameobject come back once I stop the game

swift crag
#

Yes.

uncut bay
#

alright thx

swift crag
#

you'd have to try pretty hard to permanently destroy objects

amber nimbus
wintry quarry
swift crag
#

It's actually easier to accidentally create new ones (if you spawn a game object in OnDestroy, for example)

uncut bay
#

oh

swift crag
#

yeah, Destroy is a static method defined in UnityEngine.Object. So the explicit way to refer to it is UnityEngine.Object.Destroy

You often write Destroy(...) because you're writing code in a class that has Object as a parent.

lone finch
swift crag
#

you get all of the non-private methods from your parent classes

#
GetComponent<MyComponent>();
Destroy(gameObject);
FindObjectOfType<Collider>();

all of these are methods your class inherited

#

So if you ever write code that isn't a MonoBehaviour, you'll have to use the full name for those methods

#

i was confused by that at first

#

"where did Destroy go?"

uncut bay
#

ok thank you!

#

I'm not at the stage of going outside monoBehaviour but hopefully I'll get there šŸ˜…

#

why does a gameobject titled EventSystem sometimes pop up in my hierarchy?

slender nymph
#

the EventSystem is used by the UI to detect clicks and send events to the objects

uncut bay
#

doesn't the computer do that all the time

rocky canyon
buoyant knot
#

no

uncut bay
#

why does unity need something for it

rocky canyon
#

no limits

buoyant knot
#

the computer detects inputs.
Unity takes inputs to actually activate UI elements

#

that is what eventsystem is for

uncut bay
#

alright

uncut bay
slender nymph
swift crag
#

The EventSystem has several important jobs

rocky canyon
#

yea ur computer realizes clicks.. but in that sense if you click the game window it just focuses it.. (maximizes it, or brings it to front).. thats all it'll do.. Unity has to figure out what those clicks mean for itself ... the EventSystem.. is Unity's

swift crag
#

It keeps track of the currently selected game object and figures out which events to send

uncut bay
#

oooh ok

rocky canyon
#

Windows (the PC) has its own type of click, input grabbing stuff, but thats Built into ur Operating System

uncut bay
#

so it just takes the input and turns it into something Unity can deal with?

swift crag
#

right.

#

Your computer doesn't have a notion of "currently selected object" at all

rocky canyon
#

ur computer could care less what code is running within unity

swift crag
#

when you click on a file in Explorer and it gets highlighted, that's Explorer deciding what's currently selected

rocky canyon
#

its it's own seperate sytem

buoyant knot
#

if you make a click at (20,250), how is unity supposed to know that means ā€œactivate the button #69ā€

uncut bay
#

fair enough

#

can I delete it from my hierarchy?

#

it recently appeard

buoyant knot
#

i think i’m going to bite the bullet and upgrate my old classtypereferences package from 2016 to the recent one. wish me luck

uncut bay
#

and wasn't there earlier

buoyant knot
uncut bay
#

ight thx

buoyant knot
#

then none of your buttons will work. just like before

uncut bay
#

I didn't create any buttons tho

buoyant knot
#

then you have nothing to lose

uncut bay
#

šŸ‘

rocky canyon
#

its just Unity trying to help ya out a little

swift crag
#

yeah, the editor will do it for you

uncut bay
#

oh ok that makes sense

#

I tried using canvas but it doesn't work how I want it to, I'll just watch a video on how to use it later

swift crag
#

you should read the UI docs when you're ready to do UI work

rocky canyon
buoyant knot
#

canvas is how you make a UI

rocky canyon
#

make sure ur canvas is set up correctly... should be okay

#

Overlay, Scale with Screen Size (then set ur target resolution)

safe root
#

How do I instantiate a object on whatever my last raycast hit?

swift crag
#

the position that the hit occurred at

rocky canyon
#

just use that to get its transform coord's and spawn the prefab there

#

šŸ‘

buoyant knot
#

and then you instantiate a gameobject, it has a transform

#

and you can set transform.position. or rigidbody.position

rocky canyon
#

when making mobile joystick.. is it common practice to have it position itself to where u click on the screen

#

or is it better to have it fixed?

buoyant knot
#

mobile joysticks are always ass

rocky canyon
#

lmao

#

i know.. BUT.. mine will be different

#

šŸ˜µā€šŸ’« lol

buoyant knot
#

you’re asking if a pig looks prettier with a blue dress or a pink dress.

swift crag
#

I'd rather have the joystick stay in place. Trackball-style input would be fine if you want to be able to touch anywhere to start the input

rocky canyon
#

guess ill do both

#

and have a setting

#

im sure that will appeal to most

buoyant knot
#

i would not have joystick input. find a different way to do input

rocky canyon
#

could get my hands on my Gyro..

#

gotta figure out how that inputs/outputs

safe root
swift crag
#

yes, which is a position

#

what is the problem?

buoyant knot
#

gyro controls are fun. except for the 99% of people who hate them

swift crag
#

are you trying to do Instantiate(foo, hit.point) ?

rocky canyon
#

transform.position = Vector3;

#

ez

rocky canyon
#

ive missed all the hype..

#

ready to be included

#

lol

buoyant knot
#

what type of game is it that needs joystick input on mobile

rocky canyon
#

its a godcam

rocky canyon
safe root
swift crag
rocky canyon
#

its all setup for mouse and keyboard... soo im experimenting with changing it over to Mobile controls

#

and learning it all at the same time

buoyant knot
#

if you put gyro controls, you will be stabbed

swift crag
#

have a look at its properties

safe root
swift crag
#

Yes, because RaycastHit isn't a Vector3

swift crag
buoyant knot
#

people will think it’s cool for like 5 minutes tops, before the gyro control being disorienting takes over, I think

safe root
swift crag
#

The Transform of the rigidbody or collider that was hit.

#

This is not the position in space you hit

#

It's the Transform of the thing you hit

buoyant knot
#

you might do something weird, like gyro controls angle, and then tap screen to move camera. but i warn you that gyro controls for that have a very high chance of going south

rocky canyon
buoyant knot
#

my recommendation would be left/right buttons to pan around the current focal point, and tap screen to move to a different spot

swift crag
#

if you use hit.transform, then you're ignoring where you actually hit the collider

rocky canyon
#

swipe left and right up and down.. to move around

#

pinch to zoom, ur basic stuff

swift crag
#

you'd just get the position the collider is sitting at

buoyant knot
#

swipe might be a good way tbh

safe root
swift crag
#

Right.

rocky canyon
#

welp, guess i oughta get learning the touch input stuff

#

bound to happen eventually

buoyant knot
#

press hold drag => move around with fixed point. double tap to translate to target pos

sage mirage
#

Hey, guys! I have a question. I am not sure of how to make particle effect to happen when I click any button on my game. Could you please guide me somehow?

safe root
buoyant knot
#

do you have experience with pymol?

rocky canyon
#

then you can instantiate that prefab at the position of the button...

sage mirage
rocky canyon
#

or even better u can have it parented to the button (so its always in place)

#

and just enable and disable it

sage mirage
#

@rocky canyon Can I use in the inspecto an OnClick event?

rocky canyon
buoyant knot
#

i feel like there should be a package for 3D panning around with mobile touch controls

rocky canyon
#

just call the Function when u click the button

buoyant knot
#

this should be such a common thing, that you should be able to buy it or find it

rocky canyon
rocky canyon
#

(like spawning a particle effect)

sage mirage
#

Check my code how I did that:


private void Start()
{

}

private void Update()
{

}

public void ClickParticleEffect()
{
    Instantiate(clickParticleEffect, transform.position, clickParticleEffect.transform.rotation);
    Debug.Log("Click particle effect is enabled!");
}```
twin bolt
#

In my game the player falls really slow. Could this code be why? ```
float horizontalInput = Input.GetAxis("Horizontal");
float verticalInput = Input.GetAxis("Vertical");

        Vector3 forward = playerCamera.transform.forward;
        Vector3 right = playerCamera.transform.right;
        forward.y = 0f;
        right.y = 0f;  
        forward.Normalize();
        right.Normalize();

        Vector3 desiredMoveDirection = forward * verticalInput + right * horizontalInput;

        rb.velocity = desiredMoveDirection * playerSpeed;```
buoyant knot
#

well, that’s your velocity

#

there is no falling

rocky canyon
#

as someone already mentioned.. that code doesn't even make ur player fall

twin bolt
#

How could i fix it?

buoyant knot
#

wdym? it isn’t broken

rocky canyon
#

turn off gravity?

safe root
#

How can I stretch a gameobject from one object to my character?

rocky canyon
#

lol no clue tbh.. we need to know more about ur setup

#

the character, what is it, what its supposed to do?

#

etc

buoyant knot
#

it successfully sets your player velocity based solely on your move input

twin bolt
#

I want the player to fall, i have a vent scene in my game, where the player has to navigate vents, and their is a drop part.

#

I made this movement setup without this part in mind.

buoyant knot
#

well, you’re just setting player velocity

#

there is no gravity

elfin dew
#

hello, I have a big problem, I'm making a 2d racing game, I'm with the AI driving, and when it's time to start, the AI goes all the way to the right, I pass the 3 scripts that have to do with the AI, the AIPathWay script, it's the one that creates the line for the AI to follow

twin bolt
#

Rigidbody gravity wont work?

buoyant knot
#

you’re setting velocity every frame.

buoyant knot
#

force changes velocity over time

rocky canyon
#

ur setting Y properties of ur force to zero

rocky canyon
twin bolt
rocky canyon
#

since forward and right are the only forces ur using in ur velocity

#

ur Y is always gonna be zero.. so gravity will be cancelled out

buoyant knot
#

you can’t just randomly guess your way through code, man. you need to think about what is happening to your variables

twin bolt
#

ok

rocky canyon
#

for gravity i would just tack on a 9.8 in there somewhere

#

-9.8 on the Y

#

would be gravity

#

BUT, i still wouldnt know why its slowly falling in the first place tbh

buoyant knot
#

he has a more fundamental issue of not knowing how this works

rocky canyon
#

ya, my recommendation would be to find a couple of movement tutorials.. that match what u wanna do..

buoyant knot
#

tacking on a 9.8 won’t solve anything

rocky canyon
#

watch em and follow along to atleast one of em.. even if in a different scene and script

buoyant knot
#

because he isn’t in control of his code

rocky canyon
#

get ur head around how the velocity works

rocky canyon
#

its not too hard tbh

buoyant knot
#

he needs to understand how velocity, force, and acceleration work

#

otherwise, he will never make it through

rocky canyon
#

yup, player controllers are pretty important.

#

and no one gets it right first

#

took me many controllers to where i felt comfortable enough to code my own.. w/o just ripping it off the internet somewhere

buoyant knot
#

every fiixed frame, unity:

  1. add forces * fixedDeltaTime / mass to rigidbody velocity
  2. Simulate physics with forces from collisions etc
  3. change rigidbody velocities based on collisions
upbeat stirrup
#

Is it okay to lerp a rigidbody's velocity?

safe root
#

How can I stretch a object from where my character is to a object that they clicked on?

buoyant knot
twin bolt
#

I'll still watch some videos though

buoyant knot
#

or rigidbody.MovePosition, to a position that I calculate hsing Lerp

rocky canyon
#

some advanced curve stuff going on, but the guide is still a good one to follow and let simmer in the back of ur mind

elfin dew
#

need help pls

alpine cosmos
#

Hello! I have a question about showing and interacting with 3d object in UI, I used the method with render texture + camera + separate layer to get my 3d objects to show in the UI, but is it possible to somehow interact with the objects? Or should I change my approach if I want interactable 3d objects drawn over a UI?

rocky canyon
# safe root How can I stretch a object from where my character is to a object that they clic...

Not sure I totally understand what ur talkin about.. but the key to what i think u mean is Pivots..
I make sure most of my pivots are correct when I model.. but sometimes I use parent and children links in Unity to create my own..
When you scale, it'll scale from the pivot.. so if you use a parent object.. and move the child over where the pivot is to the side.. when you scale that main parent.. the child will scale too.. only growing from the pivot point (the parents position).. like so.

alpine cosmos
rocky canyon
#

as long as it has a Collider

#

theres not really a need to force it to be a UI element

#

unless you really want to

wintry quarry
#

If you're using NavMeshAgent how would AddForce work? You can't use both Rigidbody physics and NavMeshAgent at the same time. They will conflict.

rocky canyon
wintry quarry
#

as long as you have a Physics Raycaster on your camera

rocky canyon
#

game changer for stuff like Hovering Objects

#

ya, wouldnt you need to

  • disable the navmeshagent
  • make the jump
  • reenable the navmeshagent
wintry quarry
#

yes, as mentioned befoire, you're mixing Rigidbody and NavMeshAgent

rocky canyon
#

i also ask?? b/c im not quite sure how the navmesh deals w/ the agent being ripped away from it and re-enabled..

#

havent done that yet

wintry quarry
#

you didn't disable it

#

you did isStopped = true

rocky canyon
#

u gotta disable the component completely

#

no no, u get a reference to the NavMeshAgent

#

and disable it like any other component

#

thatComponent.enabled = false;

#

its like unticking the box in the inspector

#

and re-ticking it after u do ur jump rigidbody voodoo

wintry quarry
#

you are doing enemy.enabled = true; immediately after adding the force...

rocky canyon
#

^ all thats gonna happen in a snap of the fingers (1 frame)

wintry quarry
#

it's also unclear why this is happening in a loop over the colliders in your overlapsphere

#

that's really weird

#

Esepcailly since the NavMeshAgent reference seems to come from elsewhere

rocky canyon
#

im guessing its an inspector filled variable

wintry quarry
#

It shoukldn't be. It should probably be coming from the OverlapSphere

#

Also:
m_Rigidbody.AddForce(Vector3.up * 200f * Time.deltaTime);
You should NOT be multiplying deltaTime in there

rocky canyon
#

ohh yea! i didnt even see that

wintry quarry
#

And you also should be using ForceMode.Impulse.

rocky canyon
#

bad bad.. lol

#

Rigidbody stuff runs on its own time line.. its running in FixedUpdate.. its fixed for physics to be able to accurately run..
theres no need to use Time.deltaTime b/c your not scaling for different framerates... the physics runs the same on 100fps as it does on 40fps

swift crag
#

deltaTime is just flat-out wrong here, from a mathematical standpoint

#

the default AddForce mode is ForceMode.Force

#

the value you provide is interpreted as...force

#

how hard you are pushing on the rigidbody

rocky canyon
#

i bet his forces are HUGE

swift crag
#

the amount of force you're exerting doesn't depend on how long each frame is

#

if I'm pushing with 100 newtons of force, it doesn't matter if my timestep is 0.001 seconds or 0.1 seconds

#

i'm always pushing with exactly 100 units of force

#

also, yes, ForceMode.Impulse would be the correct choice here

#

when you use that force mode, the value you provide is interpreted as a change in momentum

#

it's an instant "whack" that makes the object move

rocky canyon
#

lol, love the terminology..

swift crag
#

using deltaTime and not using ForceMode.Impulse means that the resulting change in velocity is really, really tiny

rocky canyon
#

Instant Whack

swift crag
#

you're pushing for one frame and also pushing with a very small force

slender nymph
#

do you have both a NavMeshAgent and a Rigidbody on this object? šŸ¤”

#

is the rigidbody kinematic?

#

well then it's probably because you enable the navmeshagent on the next frame

#

actually you're probably doing it on the same frame

#

well what happens when you hit two colliders with your OverlapSphere but only the first has the Player tag?

#

the answer is that it reenables the navmeshagent

#

same thing if you hit the player and jump one frame but then do not detect it with the overlapsphere on the next frame

#

don't immediately re-enable the navmeshagent. keep it disabled for the entire duration of the jump

#

or the better option would be to not rely on the navmeshagent to move the enemy at all but instead use it just to get the path to where you want to move and use the path to move via the rigidbody

#

well yes, a kinematic rigidbody is not affected by forces so AddForce won't work on it

#

well that's all kinds of wrong

#

a position is not a direction and you shouldn't be using deltaTime in your forces

knotty gust
#

is there a way to recreate this line of code using a string path instead of a textasset: GameData gData = JsonUtility.FromJson<GameData>(JSONFile.text);

slender nymph
#

then don't use transform.position to move the player

slender nymph
desert elm
#

I want to repeat this code until its interrupted/hits a non "Forest" tagger collider or ends up at the target location.
but, of course, there is a compile error. Is there a way I can make unity ignore this?

slender nymph
#

pass the object to the method as a parameter

desert elm
#

thanks

buoyant knot
#

this sounds like an IEnumerator could help here

#

you just have this very strange *2 in the middle

#

also, the distance += could all be before the if statements

wind steeple
#

i watched a tutorial on how to add a certain set of physics for my games physics engine the tutorial was by gamesplusjames and during the tutorial he shows how to code the the camera to whatever your mouse direction is is the direction that the object will go and the camera aswell i dont know how to fix it

slender nymph
#

!code

eternal falconBOT
wind steeple
slender nymph
eternal falconBOT
wind steeple
slender nymph
#

if only there was some sort of bot that linked a bunch of resources that explain how

wind steeple
#

I got six errors says invalid expression term ā€˜/ā€˜

slender nymph
#

configure vs code and it will underline those errors for you

polar acorn
wind steeple
#

Ok

onyx blaze
#

Someone can help me?
I'm trying to resize my boxcollider at runtime, but aren't working
I teste with Debug.Log and I'm getting the right values
My GameObject are resizing the rect without problems
But only the box collider not resize
How can I solve it?

fair sleet
#

would anyone here know how to solve the error of"Object reference not set to an instance of an object"

dense root
slender nymph
hexed terrace
onyx blaze
#

I'm trying to set the collider in the same size that the color bars

timber tide
#

could just do a distance comparison

grizzled acorn
#

What is recommended best practice for moving a character with rb in 3D space?

slender nymph
fair sleet
slender nymph
#

well for starters your !IDE is not configured

eternal falconBOT
wise oyster
#

How can I get a random element from each dimension of this array?

wintry quarry
slender nymph
wise oyster
fair sleet
wintry quarry
#

Something like:

// for each dimension...
for (int i = 0; i < grid.GetLength(0); i++) {
  // get random element:
  int randomIndex = Random.Range(0, grid.GetLength(1));
  int randomVal = grid[i, randomIndex];
  Debug.Log($"Picked {randomVal} which was element {randomIndex} from row {i}" );
}```
#

I think you mean from each "row"? @wise oyster

fair sleet
slender nymph
#

use == instead. but get your IDE configured first as it is a requirement in order to get help here

fair sleet
#

alright thank you

onyx blaze
arctic harbor
#

is there a scripting property or something to figure out what component is triggering a OnCollisionEnter2D(Collision2D other) call? for some reason my player character is dying twice to some hazards

wise oyster
slender nymph
rich adder
onyx blaze
#

I tested with the object and not works too

wintry quarry
wise oyster
#

Thanks šŸ™

slender nymph
# onyx blaze To tests

why don't you try printing some useful information, such as where the rect is, its size, and the position you are checking

arctic harbor
#

forgot to look at documentation, thanks

fair sleet
slender nymph
#

do you currently have syntax highlighting for unity types?

onyx blaze
slender nymph
#

oh my god you can print things outside of that specific if statement you know

onyx blaze
#

I tested with a value, but no debug in the console

slender nymph
#

because your condition isn't true and you aren't bothering to print useful information outside of the if statement to determine why it isn't true

onyx blaze
#

Isn't enter in the next if

#

The next "if" should debugged when put the mouse inside de transform, right?

slender nymph
#

ah yes, the number 0 is definitely useful information that will tell you where your rect is, its size, and also the position you are checking. good job šŸ‘

wintry quarry
#

that being said - if you're just trying to detect when the mouse enters a given UI element, this is a very inefficient way to do it. There is a UI Event System with callbacks like OnPointerEnter / OnPointerExit etc.

onyx blaze
slender nymph
#

mate i already told you to print those specific things and you went and printed a useless number instead

arctic harbor
#

does the child of an object automatically inherit the tags of its parents as well? i have a player with a "Player" tag, and it has a child object that is untagged. i have a hazard set to respawn the player with OnCollisionEnter2D if the incoming object has tag "Player", but it's also detecting the child object

rich adder
onyx blaze
slender nymph
#

i just suggested they could instead just check if the center of that other object is inside the rect instead

onyx blaze
#

I was trying to get Rect.width and Rect.height to change the BoxCollider size

arctic harbor
# rich adder ~~no~~ iirc the child collider becomes part of the parent rigidbody, so it prob ...

huh? i never said anything about a rigidbody. the OnCollisionEnter2D is detecting the player's box collider, and an edge collider attached to th player's child object. i have OnCollisionEnter2D check for the "Player" tag but the child object isn't tagged. if i Debug.Log(other.gameObject.name); it outputs the player both times, but if i Debug.Log(other.collider); it outputs the player's box collider once and the child's edge collider once

queen adder
#

Is there a simple way to make npcs wander in a city setting? I say "city setting" because I wouldn't want them just walking into walls, trees, fences.

cursive thicket
#

how can i use vfx after destory game object and write in same script

#

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class getTreasure : MonoBehaviour
{
public myGameManager gm;
AudioSource audio;
private void Start()
{
Debug.Log("get treasure...");
audio = gameObject.GetComponent<AudioSource>();
}

private void OnTriggerEnter(Collider other)
{
    if (other.gameObject.CompareTag("Treasure"))
    {
        gm.AddScore();
        audio.Play();
        Destroy(other.gameObject, 3f);

    }
}

}

eternal falconBOT
rich adder
queen adder
slender nymph
#

do you have any pathfinding set up? or is the actual question "how do i set up pathfinding so that i can then make my enemies wander around"?

arctic harbor
rich adder
arctic harbor
#

the player does

rich adder
#

so why did you say "Who said anything about a rigidbody ?"

#

I told you parent rigidbody has a child collider, that collider is part of the player rigidbody

#

and will call the events

cursive thicket
#

i am kinda dump on C# notlikethis

frigid sequoia
#

Guys, don't know where to ask this; but how do I get unity physic to freaking work properly? Like I am scalating an object (like some walls appearing and dissapearing and items on them seem to decide at random if they want to detect their collisions or not

wintry quarry
arctic harbor
#

well then how do i make OnCollisionEnter2D ignore rigidbodies then...i just want it to detect the parent's box collider and nothing else..

frigid sequoia
#

I have tried to use FIxed and Late Update and the different collision detections from rigidbodies

rich adder
slender nymph
frigid sequoia
wintry quarry
#

Anything you do outside the Rigidbody is making an end run around the engine

#

it's basically going to recreate the object at the different size in the physics engine when you do that

#

What would you expect to happen when you scale an object but it collides with something? Should it unscale them? How would it know to do that when you're scaling things through the Transform?

arctic harbor
arctic harbor
#

does that not compare the gameObject's tag?

wise oyster
#

Made a mistake, I just need a random value from the grid array to use for these variables.

slender nymph
wintry quarry
wise oyster
frigid sequoia
# wintry quarry What would you expect to happen when you scale an object but it collides with so...

If you are scalating something progresively frame by frame and a rigidBody is on top of it; the collider of the scaled item would clip through the rigidbody; the engine should now detect that a rigid body is clipping and push it towards the closest edge to stop clipping; that's basically what it is doing when the item is moving prior to the scale; but if it is still, it doesn't seem to initialize physics at all

wise oyster
wintry quarry
#

It's not great at that

#

There won't be any actual momentum or force simulation involved, just a panicked depenetration

wintry quarry
rich adder
grizzled acorn
#

How to make a 3D chracter move best practice?

frigid sequoia
rich adder
wintry quarry
wise oyster
hollow zephyr
#

Quick question, I am making a development build for WebGL to debug some things. The issue is that every time I press the Build button, it wants me to select a folder and build from scratch..... how do I set up incremental builds?

weary summit
#

Is it a good idea to learn how to script by using a chatbot or is it inefficient? Like for example make use of the manual instead?

north kiln
fringe coral
#

Hello

wise oyster
#

lmfao

#

so i use the variables for randomItem

#

and do it twice

rich adder
#

make a method

wise oyster
#

ur right

dense root
#

Anyone know how to change the color of the line render being drawn? The "Color" option at the right is set to black but it's still displaying purple.

north kiln
#

it's displaying shader error magenta

dense root
#

Oh, thank you

deft venture
#

private void AIControl()
{
if (ball.transform.position.y > transform.position.y + 0.25f)
{
playerMove = new Vector2(0, 0.5f);
}
else if (ball.transform.position.y < transform.position.y - 0.25f)
{
playerMove = new Vector2(0, -0.5f);
}
else
{
playerMove = new Vector2(0, 0);
}
}

I'm trying to make pong ai and the movement is kinda bad and choppy, is there a way to make it more smooth?

slender nymph
eternal falconBOT
deft venture
#
using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerMovement : MonoBehaviour
{
    [SerializeField] private float movementSpeed;
    [SerializeField] private bool isAi;
    [SerializeField] private GameObject ball;

    private Rigidbody2D rb;
    private Vector2 playerMove;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        if (isAi)
        {
            AIControl();
        }
        else
        {
            PlayerControl();
        }
    }

    private void PlayerControl()
    {
        playerMove = new Vector2(0, Input.GetAxisRaw("Vertical"));
    }

    private void AIControl()
    {
        if (ball.transform.position.y > transform.position.y + 0.25f)
        {
            playerMove = new Vector2(0, 0.5f);
        }
        else if (ball.transform.position.y < transform.position.y - 0.25f)
        {
            playerMove = new Vector2(0, -0.5f);
        }
        else
        {
            playerMove = new Vector2(0, 0);
        }
    }

    private void FixedUpdate()
    {
        if (isAi)
        {
            AIControl();
        }
        else
        {
            PlayerControl();
        }
        rb.velocity = playerMove * movementSpeed * Time.fixedDeltaTime;
    }
}
#

that is my pong code

short hazel
#

You execute AiControl (or PlayerControl) twice

timber tide
#

probably a bunch of resources on pong AI which you should dig into

short hazel
#

Once in Update, once in FixedUpdate - this does not seem normal

wintry quarry
#

You also should not be multiplying Time.fixedDeltaTime into your velocity

visual hedge
#

Hello everyone.
Enemy is chasing the player and I want to fire some methods if enemy has got into the certain range with player.
How do I do that?

    {
        agent.SetDestination(player.position);
        if (animator.transform.position - player.position < agent.stoppingDistance)
        {

        }
    }

The trouble is that agent.stoppingDistance is a float and player and enemy positions are Vector3s.

#

or do I just add some sphere collider to enemy and if that triggers, I fire the events?

timber tide
#

what's wrong with distance

visual hedge
timber tide
#

if you know they're 3 units away enough to trigger a method, wouldn't that be fine for your requirements

visual hedge
timber tide
#

you know the positions already, you just grab them from the player and the enemy transforms

visual hedge
#

that's done in the code I have already, yes

#

and then I compare them and I have to find out the distance...

timber tide
#

yep

visual hedge
#

and that's where I have problem

#

oh wait a second, I think I saw how to solve that somewhere )

timber tide
#

you've really have all the information already

visual hedge
#

Okay, I found it šŸ™‚ Sorry

#

Vector3.Distance(transform.position1, transform.position2) is the answer to my question basically )

timber tide
#

But you already do that with your original code without the method

visual hedge
#

nevermind, case resolved

timber tide
#

right distance method does skip that step for you

visual hedge
#

yeah šŸ™‚ I am too noob to explain that the right way... but anyway I found if in the code I already have so that basically it šŸ™‚

past brook
#

trying to create a jump pad that when entered the pad runs a script that adds an upward force to the player. idk what im doing wrong, game will run but doeesn't run script

polar acorn
past brook
#

i tried it but then i get new error about no otherRigidbody def

polar acorn
slender nymph
eternal falconBOT
ivory bobcat
sacred egret
eternal falconBOT
slender nymph
sacred egret
slender nymph
#

well that certainly wasn't necessary. the canvas is in screenspace and does not need to have the camera resized to match its size

queen adder
#

how do i move a object towards a local rotation

slender nymph
#

depends on what you mean by that

ivory bobcat
queen adder
#

for instance, my camera has a head bob effect that moves its position towards the world and not the camera's view

slender nymph
#

okay so you just want to move the object relative to its own rotation and not relative to the world axes, right?
so that will sort of also depend on how you are moving it, but you can typically just use something like transform.TransformDirection to change a local space direction to world space

deft venture
#

The pong ai jitters when i set the movement speed very high and also even at low speeds it's kinda slow. I don't really know how to implement delta time I kinda just followed a tutorial so I only know how some parts of the code work.

using UnityEngine;
using UnityEngine.InputSystem;

public class PlayerMovement : MonoBehaviour
{
    [SerializeField] private float movementSpeed;
    [SerializeField] private bool isAi;
    [SerializeField] private GameObject ball;

    private Rigidbody2D rb;
    private Vector2 playerMove;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        if (isAi)
        {
            AIControl();
        }
        else
        {
            PlayerControl();
        }
        rb.velocity = playerMove * movementSpeed * Time.fixedDeltaTime;
    }

    private void PlayerControl()
    {
        playerMove = new Vector2(0, Input.GetAxisRaw("Vertical"));
    }

    private void AIControl()
    {
        if (ball.transform.position.y > transform.position.y + 0.25f)
        {
            playerMove = new Vector2(0, 0.5f);
        }
        else if (ball.transform.position.y < transform.position.y - 0.25f)
        {
            playerMove = new Vector2(0, -0.5f);
        }
        else
        {
            playerMove = new Vector2(0, 0);
        }
    }
}
ivory bobcat
slender nymph
#

shouldn't be using deltaTime or fixedDeltaTime for that at all. velocity is already expressed in units per second

ivory bobcat
#

If interpolation should be relative to fixed delta time, consider doing the arithmetic in FixedUpdate - Input needs to be aquired in Update though.

true pasture
#

I need help with debugging whatever I click on. I have 2 buttons in my scene but only one can be clicked. When I try to click the other nothing happens. I want to log what im clicking on thats stopping the other button from working. Both buttons work when the other is turned off. So I aassume one button is covering the others hitbox but I can't see anything like that. How could I log what I clicked on?

#

or even what im hovering over

slender nymph
#

just look at the event system's preview window, no need to print what is being clicked on when you can just see it

queen adder
#

WasPressedThisFrame

#

how do i make this function actually return something

#

it never does

slender nymph
#

at a guess i'd say you're probably not enabling your actions

wintry quarry
#

actions.Enable();

true pasture
#

Ive tried using that window, but all it shows me is the selected object. I dont think its something selectable thats blocking me. Is that possible?

north kiln
#

I have no idea why they made the Input System have useless results in that window; it's so important

#

and yet... that

#

You can probably add a breakpoint in InputSystemUIInputModule.ProcessPointer after it calls PerformRaycast

#

and look at the eventData's pointerCurrentRaycast result

queen adder
#

my actions are enabled

slender nymph
#

well then you need to show more context

spiral glen
#

Is there a place that explains what each vector does? (I'm having trouble explaining it)

dark oak
#

umm guys, i just installed unity 2019.4 on windows 7 and its not opening What should i do?

spiral glen
slender nymph
wintry quarry
#

That's like saying "is there somewhere that explains every number?"

spiral glen
#

mb

cosmic dagger
wintry quarry
#

Please explain 5.346 what's it all about?

cosmic dagger
# spiral glen mb

You can look at the Unity docs for Vector2 and Vector3 structs (if that is what you mean) . . .

spiral glen
dark oak
#

guys can i ask a question?

slender nymph
#

this is also a code channel

eternal falconBOT
#
šŸ“ Logs

Documentation

Editor logs

Windows: %LOCALAPPDATA%\Unity\Editor\Editor.log
MacOS: ~/Library/Logs/Unity/Editor.log
Linux: ~/.config/unity3d/Editor.log

Unity Hub

Windows: %UserProfile%\AppData\Roaming\UnityHub\logs
Mac: ~/Library/Application support/UnityHub/logs
Linux: ~/.config/UnityHub/logs

cosmic dagger
muted wadi
#

how could I approach sending out a raycast from the camera that is the exact size of the camera view?

#

as in everything that you can see, is being hit by a ray

cosmic dagger
wintry quarry
muted wadi
#

are those different?

cosmic dagger
slender nymph
#

those do have volume, but unless you are using an orthographic camera they won't hit everything you see because the view is not perfectly rectangular

cosmic dagger
#

So, let's think about how those would cast in a scene . . .

wintry quarry
muted wadi
slender nymph
#

for what purpose

wintry quarry
#

Send a few sample rays I guess. What are you trying to actually accomplish?

muted wadi
#

have you guys seen that one episode of doctor who with the weeping angels?

cosmic dagger
#

Why do you need a cast for the entire camera view?

wintry quarry
muted wadi
#

yes

#

am i going about it the wrong way?

wintry quarry
#

Probably would just do an OverlapSphere followed by checking the angle difference between the player's forward direction and the direction to any angels returned from the OverlapSphere

#

If it's outside some angle threshold then it can attack

#

You wouldn't want players with higher FOV to have an advantage anyway so I feel this would be superior to perfectly checking if it's in camera view

muted wadi
#

i was going to make a specified FOV anyway so thats not a problem

muted wadi
wintry quarry
#

Imagine a cone sticking out of the player's face. If the angel is touching it, it's visible

muted wadi
#

i see