#š»ācode-beginner
1 messages Ā· Page 135 of 1
Wait, really?
I incorrectly thought that Start ran on the same frame as Awake for in-scene objects
Yes.
That would be nightmarish
this is also why the game freezes if you get into an infinite loop
So it's all just one single callstack, no syncing of various parallel operations?
unity is single threaded
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.
Then Instantiate has to nclude a call to Awake inside of it no?
Yes, it does
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)
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
Right that's what I was looking at
Well this puts a lot of things in order. Thanks
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);
}
}
anyone know what return method should be used on an enumerator if you want it to stop looping once it reaches a specific condition?
yield break;
Would break the coroutine. To break a loop, use regular break.
yea the issue is that its not looping its just moving on to the next condition?
So it's looping or not looping? Maybe provide some actual context.
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
right i want it loob but until it reaches a specific condition
Show us what you've tried
then use that condition to control the loop...?
yes, please show us what you're doing
!code
š Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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?
Maybe decrease speed is zero if you aren't able to escape the first loop
the entire script would be helpful here
yea
its not cause the meter does deplete but when it hits 0 it just keeps looping
Where's the actual error/unwanted behavior?
the if statement isn't being valued
Try logging the value
I'm guessing you aren't ever able to leave the loop at this point
https://gdl.space/humakeqiwo.cs here is the entire code but is kinda messy
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.
which value exactly
GetTransformMeterNormalized()
that's from another script, so we don't know what it's doing
transformMeter.GetTransformMeterNormalized()
public float GetTransformMeterNormalized()
{
return transformMeter / maxTransformMeter;
}
What did the value print?
logging the value in the while loop will also reveal if the code is even running in the first place
Dude had a log in there before but it wasn't printing anything important
how would i do that?
By logging the value?
https://gdl.space/ujihivemep.cs lookie what I made 
An oppsie? 
just a simple script to catch input š
Is the Any Direction Down function intended to be processed on every call?
its logging the values properly its counting down as it should
Even if no keys are pressed
So the loop eventually ends?
Dunno. Just making sure it's intentional
nope doesn't look like its looping its just giving various 1000th's of a value
Show the logs (an image of the console tab)
You said it's decreasing, this implies it's going to zero
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
So figure out why it's not properly decreasing.
not code question
google sorting layer and sorting order
Either the decrease function is broken or the value you're calling it with is decreasing and never exceeding what's remaining.
priority: layer>order>z-value
Ok thanks
anyone know why I can't drag a prefab onto the scene in 2d unity?
you should be able to. are you dragging a prefab file from your project tab?
that is not a prefab?
that is a texture
oh
yea its weird it's decreasing the value by 20 at a time from 100 but then just bugs out ill figure out the issue it should fix thanks for the insight.
it is texture not prefab, prefab is gameobject in disk
a texture is a picture
a gameobject is an entity with components on it in the scene
I did the same with another image and it worked that time
one of those components can display a texture
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?
no
I thought you couldnt drag textures
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
that's pretty cool, I dragged the texture into the scene and it did the empty gameobject thing automatically
you should avoid doing that outside of defining a prefab, because if you edit those settings, you canāt copy paste it everywhere
I should avoid dragging the texture itself?
If I edit which settings?
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
Default sprite layer is almost always wrong whenever you build a real game, because you will use multiple layers for sprites
you would need to make a prefab
and drag the texture on the gameobject?
well, making a prefab means you make your gameobject with all the components it needs, with all the settings it needs
like, that heart gameobject is totally useless, as you canāt collider with it, it has no script, it is not in UI, etc
The proper way to do this is:
GameObject -> UI -> IMage
Then set the sprite to that heart. @uncut bay
yes
If it's not in the hierarchy then it doesn't exist in the game
i'm just tryna have 3 hearts, and individually disappear every time you touch spikes
Do you mean it's not in the hierarchy at runtime? Or just in that particular scene at edit time?
if your singleton is a monobehaviour, it needs to be DontDestroyOnLoad if you want that instance to continue to exist between scenes
Yes but do you want it to be UI? I think you probably do.
yeah, because in UI then you donāt want to use sprite renderer, iirc
or at least youāll need recttransform
you want this for UI: #š»ācode-beginner message
alright thx
I have no idea what "I'm just trying to understand which scene at i am." means tbh
what does the UI step mean?
so I create empty gameobject, then after that what
you don't create an empty GameObject. You do what I said š
they're detecting if they're playing the game or not
that's where you need to look in the menus
Right click in the hierarchy or the scene and select that menu option
GameObject -> UI -> Image
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
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;
}
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.
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)
parenting works but only if the child doesn't have its own non-kinematic Rigidbody. The best answer depends on your particular circumstances.
that wonāt be a singleton. thatās just a class that saves a ref to its most refently produced instance
It walks like a duck and quacks like a duck
It's a singleton in my book!
itās not tho? you could make 10 of them, and nothing would stop you
not singleton
And if it has kinematic rigidbody? Im working on something like coin pusher machine in unity, and when coins touch the moving part of it they get very deformed
i could use reflection to make 1000 instances of any singleton class you give me
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
deformation is happening because the parent object has non-uniform scaling. That's an easy fix. Move the scaled renderer to a separate child object and don't scale the parent itself.
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
yes, this is part of the formal definition of the "singleton pattern" that you can find on wikipedia
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
I did it and its still deforming?
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
singleton. ton that is single. only one
this is why i am asking you to not fixate on exact definitions of software design patterns
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
this is the design goal
if you just blanket let Awake() instance = this; then whenever its called twice, it will overwrite your old information
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
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
SceneManager.GetActiveScene().name
the entire point here is for this object to only exist and be accessible while in the main menu
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.
Nvm, fixed it
But it's close enough for me to understand the design intent.
note that this will create a new object and stick the singleton component onto it if it doesn't exist or has been destroyed
btw, if you are putting that in a monobehaviour class, i recommend putting a line for OnApplicationQuitting
so I'm unclear about what you mean here now.
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
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.
I haven't seen infinite loops, but I have had problems when trying to unsubscribe from singleton objects' events during OnDestroy/OnDisable
thatās usually when bad things happen
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
yeah, it keeps making one every time you try to unsubscribe, then breaking it
I got around that by just returning the existing reference if searching for an object with the right type failed
i check if singleton is null in OnDestroy
the destroyed object now looks like null, but it's a perfectly valid object as long as you don't need any Unity methods
i also always store a local ref to singleton in awake for classes that use them
do you have a Physic Material assigned to the cubes? you might need more friction
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
yeah, it's a very convenient pattern
I dont have physic material assigned, ill try that
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?
He must have declared a Unit class somewhere else.
yes
Alas, I do see the script on the left called Unit, the existence of which is implied I suppose. Thanks.
do you not see the Unit.cs there?
not until now!
It is still not working.
Yep, saw it as soon as I pasted the screenshot as mentioned. Thanks.
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
Well which object are you setting as the parent? Make sure it's Cylinder and not CylinderMesh
Is MonoBehaviour utilized exclusively for components? Is it ever necessary for a script which will not be attached to a game object?
MonoBehaviour is the way to make a custom component
if you're not making a component, it makes no sense to use it.
you can never use a Monobehaviour class that is not attached to a gameobject because you have no way to construct an instance of it
Hello what causing of this one an error
seems pretty clear - you didn't assign the playername field in the inspector
ohh thanks i was too blind to see it
Can you respond to me on a thread please??
<!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?
What am i gonna for the "Easy, Normal, Hard" toggles so it can be default to only Easy when it gets cancel it
here is unity server
Oh wrong dc my bad
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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
probably can just use a few flags
once it's down you need to then check if it's back up then down again
for a double click you basically want a small state machine
I think the new input system has some tracking for double clicking
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)
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
up
I do not understand this question.
"when it gets cancel it"
Its like reset button like
instead of saving the option of the difficulty
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
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
sorry, but what do you mean a position per pixel?
basically im establishing a route for which the cursor is attached to
Maybe use a sprite mask and dynamically update the texture pixel alphas of the mask according to the drawing
and then lerping between the positions
either way I think some kind of stencil shader shenanigans are in order
Ohh I think see what you mean, I'm googling these
movement I can probably figure out kinda, but the image reveal / cutting is whats getting me all tripped up
stencils seem like a solution, but im not too sure about getting the hard edges
also the butterfly "enemy" only moves within the unrevealed space which offers another challanage
well, if you can figure out the current problem then that shouldn't be hard
good suggestion , this is definitely getting me closer . Found couple of useful unity examples
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
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
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
That use case you gave isn't a deal breaker as long as the audio isn't too common but it's probably better to have a single audio source that's always active and swap out the clip it plays as needed
ok thank you. and Mao I already have it on my list of do does!
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
real quick for some reason i cant seem to remember to check if smth equals smth is it 1 or 2 equal signs???
obviously, you set refresh to false so the if above it can never be true again
nah it was just to test, turn out it didn't work, still did the same effect
then how do you expect a sensible answer if you knowingly post crap code?
2
it wont let me post a message with only 1 letter in it so im typing this here as well
thanks
I know there are alot of nested foreach statement and stuff but il fix it later, you can say that its just a "test"
il organize it when its finalize
Well since your error seems to be caused by this "test" I would say the time to fix it is now
yea, it was kinda shitty, i should just clean the code and then send the help
And when you do format it properly, !code
Oh is the bot not working?
You dont need to dm me, read the server rules
wsp
Since the bot isn't responding here's a link to it
I need help about 2 things
What about the Wall Street Post
I think you replied to the wrong message xd
i dont think he did
the meaning of wsp maybe
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
what did you actually mean though, im confused as well
you've never heard of the Wall Street Post? The worlds second premier financial newspaper
why is the word any ways blocked?
just hello :D
nope
dark days for the human race and getting darker by the day
of course
How exactly do I put the level I downloaded from the unity marketplace thingy into a game/project?
Package Manager
can't find anything in youtube
oh yeah
I open it on there
but than
I have no idea whats happening
I can send a sreenshot, second
write
in
full
sentences
please
Alright sorry
that aint a screenshot and I dont watch videos
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.
so post a screenshot of your unity window
@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
Oh my bad, thanks! Is it cosidered about a third party asset if its just plain loading an level?
If it's a basic question about loading assets you should start with Unity Learn really
!learn
:teacher: Unity Learn ā
Over 750 hours of free live and on-demand learning content for all levels of experience!
Thats nice, thanks!
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?
!code
š Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
don't use screenshots
also your problem is because you're using transform.eulerAngles for your logic - almost always a mistake
-5 is actually just 355. Angles repeat, you can't guarantee it'll be from 0-360 or -180 to 180.
Take the angle, add 360 to it, then modulo it by 360, then clamp it
What should I use instead?
your own float variable for pitch. Which you can clamp as you please
for 2d movement: is using velocity better or vector2.movetowards? Velocity has the advantage of no jitter when trying to go into a wall
but then how do I change rotation? transform.rotation?
localRotation on the camera for pitch
Rotate or rotation on the player body for yaw
they do diferent things
MoveTowards is just a mathematical calculation. It's not actually something that moves anything. There is no mutual exclusion between the two
Are you thinking of MovePosition on Rigidbody2D?
anyone??
ah, looks like this might be it, thanks
yes MovePosition will not respect colliders
use velocity or add forces if you want proper collision
MovePosition is intended more for something like a kinematic moving platform.
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."
Yes they'll produce collisions as in, if your moving kinematic platform hits a dynamic body, it will produce a collision
produce collision as in other rigidbodies collide into it
It will not actually cause your moving body to collide properly
okay, so velocity does seem better since i do want collisions in my case
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
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)
simple state machine maybe ?
i'll try this out!
how would you make this event only occur when the hitbox collides at the bottom?
you can use normals
what are normals?
If the Y axis is your vertical direction (most frequent case), you can check normal.y: positive values mean collision with the bottom side, and negative values mean top collisions: function OnCollisionEnter ( other : Collision ) { if ( other.gameObject.CompareTag ( "Floor" ) ) { var normal = other.contacts[0].normal; if (normal.y > 0)...
i would get the collider you hit, and use Collider2D.Distance
its the facing direction of a surface
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
yup, i was guessing it was a simple collider hence the Collision2D
but yea, might get a lil difficult for odd shapes
tilemaps
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
so each blue line is the normal for the corresponding face..
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
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
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()
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
anyone know how to use A*? my enemy finds a path to the player, but dosent move
how exactly would you do this?
im still pretty new to unity
i have coded a bit in c#
i just do not really know the unity methods
all that well
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>;
}```
š® 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...
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
You missed () at the end. (I think. lol.)
GetComponent<SpriteRenderer>();
The small mistakes are the most frustrating š
i just spent like 30 mins trying different things to find out i had the pathfinder script turned off :/
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.
https://docs.unity3d.com/ScriptReference/Collision2D-contacts.html
Not that I think the documentation is that great, but you sometimes you can get an idea from the code snippets
how did i mess this up? do i need to offset it?
camera is supposed to follow character
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;```
According to this snippet, your player shouldn't be falling at all
oh ok
Is it not following the player?
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.
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);
i think it is but its not rendering at all and i sussed out that its prolly the depth
how would that be separated?
Make a new Vector3 that uses the x and y position of the sprite, but the camera's own z.
something like this but one more value with camera depth?
You're only providing x and y to a Vector3, add the z as well.
More distance = more force? Or just constant force?
just use a multiplier... for example if you have to use 1500 you can multiply ur value by 100.. then u can use a more reasonable 15 or if 1000 u could use 1.5 etc
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)
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)
Should be more force.
So multiply instead of dividing
void OnTriggerEnter(Collider other) {
if (!other.TryGetComponent(out Hurtbox hurtbox))
return;
hurtbox.Hurt();
}
Fair enough
if TryGetComponent fails, it'll return immediately
if I used gameObject.Destroy will the gameobject come back once I stop the game
Yes.
alright thx
you'd have to try pretty hard to permanently destroy objects
this sounds like a really good way for what I am trying to achieve
Note that it's UnityEngine.Object.Destroy()
It's actually easier to accidentally create new ones (if you spawn a game object in OnDestroy, for example)
oh
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.
ive got the camera working but now it looks like either the camera or the character sprite is shaking back and forth in a headache inducing manner
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?"
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?
the EventSystem is used by the UI to detect clicks and send events to the objects
doesn't the computer do that all the time
Heck yea! This is also my preferred method
no
why does unity need something for it
no limits
the computer detects inputs.
Unity takes inputs to actually activate UI elements
that is what eventsystem is for
alright
no way, I litteraly just watched ur video on referencing scripts and gameObjects š
your operating system has no concept of what buttons and UI in unity are. unity needs something that translates clicks within its window into clicks on your UI and other objects
The EventSystem has several important jobs
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
It keeps track of the currently selected game object and figures out which events to send
oooh ok
Windows (the PC) has its own type of click, input grabbing stuff, but thats Built into ur Operating System
so it just takes the input and turns it into something Unity can deal with?
ur computer could care less what code is running within unity
when you click on a file in Explorer and it gets highlighted, that's Explorer deciding what's currently selected
its it's own seperate sytem
if you make a click at (20,250), how is unity supposed to know that means āactivate the button #69ā
i think iām going to bite the bullet and upgrate my old classtypereferences package from 2016 to the recent one. wish me luck
and wasn't there earlier
yeah. just delete it
ight thx
then none of your buttons will work. just like before
I didn't create any buttons tho
then you have nothing to lose
š
it appears anytime you Make a Canvas
its just Unity trying to help ya out a little
yeah, the editor will do it for you
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
you should read the UI docs when you're ready to do UI work
canvas is how you make a UI
make sure ur canvas is set up correctly... should be okay
Overlay, Scale with Screen Size (then set ur target resolution)
How do I instantiate a object on whatever my last raycast hit?
alright
well, you know how to find where the raycast hit, right?
the position that the hit occurred at
when u raycast it returns a Hit variable..
just use that to get its transform coord's and spawn the prefab there
š
and then you instantiate a gameobject, it has a transform
and you can set transform.position. or rigidbody.position
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?
mobile joysticks are always ass
youāre asking if a pig looks prettier with a blue dress or a pink dress.
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
i would not have joystick input. find a different way to do input
I do but it counts as a Vector3
gyro controls are fun. except for the 99% of people who hate them
are you trying to do Instantiate(foo, hit.point) ?
i just received my FIRST phone with a gyro
ive missed all the hype..
ready to be included
lol
what type of game is it that needs joystick input on mobile
its a godcam
right now its just a barebones project
Wait, my bad. Read it wrong. I need to convert the raycast to a vector3
you aren't "converting" the RaycastHit
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
if you put gyro controls, you will be stabbed
have a look at its properties
Well when i put it in the instaniate it doesn't count as a vector 3
Yes, because RaycastHit isn't a Vector3
Look at the properties a RaycastHit has.
people will think itās cool for like 5 minutes tops, before the gyro control being disorienting takes over, I think
So i'm menat to use the Raycasthit.transfrom?
Read the description for that property.
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
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
yea, ive been thinking about it.. and i think just touch controls would be best...
my recommendation would be left/right buttons to pan around the current focal point, and tap screen to move to a different spot
if you use hit.transform, then you're ignoring where you actually hit the collider
you'd just get the position the collider is sitting at
swipe might be a good way tbh
Ah, so would want use the point as it's the impact point of where the ray hit?
Right.
press hold drag => move around with fixed point. double tap to translate to target pos
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?
Thank you
do you have experience with pymol?
you can create ur particle effect and make it a prefab..
then you can instantiate that prefab at the position of the button...
It is already a prefab.
or even better u can have it parented to the button (so its always in place)
and just enable and disable it
@rocky canyon Can I use in the inspecto an OnClick event?
public GameObject buttonParticle;
public void SpawnButtonParticle(){
Instantiate(buttonParticle, ...
}```
i feel like there should be a package for 3D panning around with mobile touch controls
just call the Function when u click the button
this should be such a common thing, that you should be able to buy it or find it
im sure theres some on Github i would assume
you can, u can code the logic in a script, and just call a function inside the script to do anything u wish
(like spawning a particle effect)
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!");
}```
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;```
as someone already mentioned.. that code doesn't even make ur player fall
How could i fix it?
wdym? it isnāt broken
turn off gravity?
How can I stretch a gameobject from one object to my character?
lol no clue tbh.. we need to know more about ur setup
the character, what is it, what its supposed to do?
etc
it successfully sets your player velocity based solely on your move input
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.
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
Rigidbody gravity wont work?
youāre setting velocity every frame.
force changes velocity over time
ur setting Y properties of ur force to zero
where?
so do i remove those lines?
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
you canāt just randomly guess your way through code, man. you need to think about what is happening to your variables
ok
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
he has a more fundamental issue of not knowing how this works
ya, my recommendation would be to find a couple of movement tutorials.. that match what u wanna do..
tacking on a 9.8 wonāt solve anything
watch em and follow along to atleast one of em.. even if in a different scene and script
because he isnāt in control of his code
get ur head around how the velocity works
Okay
its not too hard tbh
he needs to understand how velocity, force, and acceleration work
otherwise, he will never make it through
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
every fiixed frame, unity:
- add forces * fixedDeltaTime / mass to rigidbody velocity
- Simulate physics with forces from collisions etc
- change rigidbody velocities based on collisions
Is it okay to lerp a rigidbody's velocity?
How can I stretch a object from where my character is to a object that they clicked on?
i normally add force towards a target velocity, and this target velocity I get by lerping
Fixed. rb.velocity = new Vector3(desiredMoveDirection.x * playerSpeed, rb.velocity.y, desiredMoveDirection.z * playerSpeed);
I'll still watch some videos though
or rigidbody.MovePosition, to a position that I calculate hsing Lerp
https://gmtk.itch.io/platformer-toolkit
when you get the time check out this.. its an interactive 2d controller example.. and lets you dive into why it works the way it does, etc
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
need help pls
Okay thanks
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?
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.
My goal is to have a mainly 2d game UI centric game, but I wan to throw/roll dice above it all when the game requires it
you can interact with 3D objects by using EventTriggers
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
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.
pretty sure I used EventTriggers on the board here.. and theres some 3D UI panels hiding in there as well
All the normal Event System stuff works with 3D objects too
as long as you have a Physics Raycaster on your camera
ya, it wasnt until after i built dozens of needless raycast scripts did i figure that out
game changer for stuff like Hovering Objects
ya, wouldnt you need to
- disable the navmeshagent
- make the jump
- reenable the navmeshagent
yes, as mentioned befoire, you're mixing Rigidbody and NavMeshAgent
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
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
you are doing enemy.enabled = true; immediately after adding the force...
^ all thats gonna happen in a snap of the fingers (1 frame)
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
im guessing its an inspector filled variable
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
ohh yea! i didnt even see that
And you also should be using ForceMode.Impulse.
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
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
i bet his forces are HUGE
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
lol, love the terminology..
using deltaTime and not using ForceMode.Impulse means that the resulting change in velocity is really, really tiny
Instant Whack
you're pushing for one frame and also pushing with a very small force
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
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);
then don't use transform.position to move the player
use the classes in System.IO to read a file and pass the contents of that file to FromJson instead
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?
pass the object to the method as a parameter
thanks
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
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
!code
š Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
also configure your !IDE
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
How do I do that
if only there was some sort of bot that linked a bunch of resources that explain how
I got six errors says invalid expression term ā/ā
configure vs code and it will underline those errors for you
Then configure your IDE and look at the underlined errors
Ok
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?
would anyone here know how to solve the error of"Object reference not set to an instance of an object"
Hey everyone I'm trying to link my drawing software to a Wacom tablet but having some trouble.
https://gdl.space/qusoxisehu.cs
why do you have colliders on UI objects? š¤
Assign an object so the reference isn't empty
Is a minigame
Each color in the bar have a collider that I use as trigger to the heart when pass trough
I'm trying to set the collider in the same size that the color bars
could just do a distance comparison
What is recommended best practice for moving a character with rb in 3D space?
just check if the center of the moving object is within the rect, no need for colliders.
https://docs.unity3d.com/ScriptReference/Rect.Contains.html
I'll try
i still dont understand honestly, i just dont know what im supposed to do to fix this. do i change where it says null to say something else?
well for starters your !IDE is not configured
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
How can I get a random element from each dimension of this array?
one random element for each dimension?
and you also cannot use the is operator to null check components and other unity objects because that operator does not use the overloaded == operator to check for unity's fake null
Yeah does that make sense
i have no idea what the means im going to be honest
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
alright so what do i need to do to fix that?
use == instead. but get your IDE configured first as it is a requirement in order to get help here
alright thank you
Isn't working
Are returning nothing to me
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
yeah from each one of these. maybe im not so aware of the terminology
why are you using the mouse position there? wasn't there some other object you wanted to check?
Collision2D gives you the information on that
To tests
I tested with the object and not works too
yeah that's more or less a "row". The code I shared should do what you want.
Thanks š
why don't you try printing some useful information, such as where the rect is, its size, and the position you are checking
forgot to look at documentation, thanks
i got it set up following the visual studio guide, what should i do now?
do you currently have syntax highlighting for unity types?
If the actual Debug.Log arent working, will not work with any info :/
oh my god you can print things outside of that specific if statement you know
I tested with a value, but no debug in the console
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
Isn't enter in the next if
The next "if" should debugged when put the mouse inside de transform, right?
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 š
this is just telling us the condition is not true. You should log the various information that goes into that condition to see why it's not true
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.
You aren't a good person to help another person
mate i already told you to print those specific things and you went and printed a useless number instead
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
no iirc the child collider becomes part of the parent rigidbody, so it prob still counts it as Player
What I want to do exactly is:
Set the BoxCollider in the same size that my RectTransform
I tried change my transform, and next frame change the boxcollider
But not works :/
their goal isn't even to get the mouse position in the rect. they are apparently just using that for testing.
they are trying to find out if another UI object is overlapping their rect for some minigame and they were originally using colliders and attempting to use OnTriggerEnter or something #š»ācode-beginner message
i just suggested they could instead just check if the center of that other object is inside the rect instead
I was trying to get Rect.width and Rect.height to change the BoxCollider size
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
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.
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);
}
}
}
!code
š Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
are you using NavMesh?
how are you getting collisions then ?
No because I've no idea what that is
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"?
the hazard has this script attached
{
if (other.gameObject.CompareTag("Player"))
{
Debug.Log(other.collider);
Debug.Log(other.gameObject.name);
//respawn player
}
}```
I'm just going to look online
which one has the rigidbody then?
the player does
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
i am kinda dump on C# 
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
Scaling objects isn't a normal physics simulation thing. It's not going to handle collisions properly with scaling generally
well then how do i make OnCollisionEnter2D ignore rigidbodies then...i just want it to detect the parent's box collider and nothing else..
I have tried to use FIxed and Late Update and the different collision detections from rigidbodies
OnCollisionEnter2D literally depends on rigidbodies to work
check the other collider's tag instead of the other gameObject's tag. the collider property on the Collision2D will always point to the collider that was hit so from that you can get to the correct object. the gameObject property will point to the gameObject of the collider if there is no rigidbody otherwise it will always be that object's rigidbody gameObject
It should detect each frame that the collisions have updated and just try to not clip with it; it seems to work significally better when the item was moving initially than when the item was just standing on the floor though
You say "it should" do that but there's no reason to expect that. The physics engine doesn't really support scaling objects. The only thing it supports is moving fixed size objects around via the Rigidbody.
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?
i don't see anything in the documentation or the inspector about a collider's tags
does that not compare the gameObject's tag?
Made a mistake, I just need a random value from the grid array to use for these variables.
surely you read my entire message about how getting the collider gets the actual collider involved in the collision whereas getting the gameobject gets the rigidbody's gameobject
Random.Range
Read your error message if you are having trouble with those compile errors
then how do I use the array
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
That's just because I havent set the variables yet
you're basically teleporting the object directly inside a body. The physics engine has to then react to this sudden inexplicable event that wasn't part of the simulation.
It's not great at that
There won't be any actual momentum or force simulation involved, just a panicked depenetration
indeed. So what's the question?
var randomIndx = Random.Range(0, grid.Length)
var randomItem = grid[randomIndx]
rinse and repeat
How to make a 3D chracter move best practice?
I don't want it to apply any physic or anything, i just want it to not end inside the object basically making the rigidbody object unreacheable
best practice in terms of what?
if at all possible this is better simulated by moving a kinematic Rigidbody upwards physically. It can be an invisible body at the top of that rectangle
it was to get a random item of the array, but this should work now š
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?
thank you :)
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?
you're getting the same random item for each axis
Hello
oh shit yeah
lmfao
so i use the variables for randomItem
and do it twice
make a method
ur right
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.
its missing material
it's displaying shader error magenta
Oh, thank you
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?
this isn't really enough context to know what is happening. how are you moving it? also !code
š Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
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
You execute AiControl (or PlayerControl) twice
probably a bunch of resources on pong AI which you should dig into
Once in Update, once in FixedUpdate - this does not seem normal
You also should not be multiplying Time.fixedDeltaTime into your velocity
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?
what's wrong with distance
it's float while positions are vector3
if you know they're 3 units away enough to trigger a method, wouldn't that be fine for your requirements
yeah, but that is the questions... how do I get from vector3 deduction to float value? š
you know the positions already, you just grab them from the player and the enemy transforms
that's done in the code I have already, yes
and then I compare them and I have to find out the distance...
yep
and that's where I have problem
oh wait a second, I think I saw how to solve that somewhere )
you've really have all the information already
Okay, I found it š Sorry
Vector3.Distance(transform.position1, transform.position2) is the answer to my question basically )
But you already do that with your original code without the method
nevermind, case resolved
oh sorry you have the direction but you need to get the magnitude from the vector ^^
right distance method does skip that step for you
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 š
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
The error tells you what you need to change to fix it
i tried it but then i get new error about no otherRigidbody def
Correct. So you need to use parameters that are on collider2D since that's what you have access to
unrelated to your issue but you need to get your !IDE configured š
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
⢠Visual Studio (Installed via Unity Hub)
⢠Visual Studio (Installed manually)
⢠VS Code
⢠JetBrains Rider
⢠Other/None
So what's suggested then try to resolve the next error
Made this for a pong game is it good(cant post it using "!code" since its too long) https://paste.mod.gg/wamdocdzmrya/0
A tool for sharing your source code with the world!
š Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
š Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
you have a whole lot of magic numbers in here and you could improve your movement by using GetAxis instead of checking each key individually
also why are your objects 100+ meters away from each other?
i made the size of the camera to big to fit the UI and made everything else bigger
well that certainly wasn't necessary. the canvas is in screenspace and does not need to have the camera resized to match its size
how do i move a object towards a local rotation
depends on what you mean by that
What's position (move) have to do with rotation? Orbiting something?
for instance, my camera has a head bob effect that moves its position towards the world and not the camera's view
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
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);
}
}
}
THANK YOU SO MUCH!!



Just use Time.deltaTime rather than Time.fixedDeltaTime.
shouldn't be using deltaTime or fixedDeltaTime for that at all. velocity is already expressed in units per second
If interpolation should be relative to fixed delta time, consider doing the arithmetic in FixedUpdate - Input needs to be aquired in Update though.
It was mentioned earlier #š»ācode-beginner message
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
just look at the event system's preview window, no need to print what is being clicked on when you can just see it
WasPressedThisFrame
how do i make this function actually return something
it never does
at a guess i'd say you're probably not enabling your actions
Well the action would have to have been triggered this frame.
Also make sure you've enabled your input actions asset
actions.Enable();
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?
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
my actions are enabled
well then you need to show more context
Is there a place that explains what each vector does? (I'm having trouble explaining it)
What vector?
umm guys, i just installed unity 2019.4 on windows 7 and its not opening What should i do?
All of em'
what do you mean by "what each vector does"?
Wdym by "each vector"?
That's like saying "is there somewhere that explains every number?"
mb
What exactly do you mean? This is not clear . . .
Please explain 5.346 what's it all about?
You can look at the Unity docs for Vector2 and Vector3 structs (if that is what you mean) . . .
No I was thinkign about something else mb
guys can i ask a question?
this is also a code channel
try #š»āunity-talk
but you probably need to check the !logs to find out why your editor is not launching
Why ask to ask? That is the whole purpose of the channel. Just make sure it is code-related . . .
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
A raycast is like a laser pointer . . .
Rays are infinitely thin lines, they can't hit everything at once, just a single thing
what about a boxcast or a spherecast?
are those different?
Well, one is a box. The other is a sphere . . .
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
So, let's think about how those would cast in a scene . . .
Sure but neither is frustum shaped.
If you're using an orthographic camera then box cast would be the shape of the camera view
yeah thats the issue i ran into, im wondering if you guys had any ideas on how I could capture the player's view in a cast (?)
for what purpose
Send a few sample rays I guess. What are you trying to actually accomplish?
have you guys seen that one episode of doctor who with the weeping angels?
Why do you need a cast for the entire camera view?
You're just trying to implement weeping angels?
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
i was going to make a specified FOV anyway so thats not a problem
also im not too great at visualing this math stuff, could you explain it in more detail please?
Basically just a conical field of view implementation for the player
Imagine a cone sticking out of the player's face. If the angel is touching it, it's visible
i see