#๐ปโcode-beginner
1 messages ยท Page 526 of 1
if you like visual stuff this was a great crash-course for me.. really got my head around the basics of c# and unity.. once i finished it I had enough info on my own to go off and find more information on the things I needed/wanted
https://www.youtube.com/watch?v=_cCGBMmMOFw&list=PLFt_AvWsXl0fnA91TcmkRyhhixX9CO3Lw&ab_channel=SebastianLague
heres also a good page w/ some basics and FAQ type stuff.. from 1 of the mods here Vertx
https://unity.huh.how/
you can also check out these as well #๐ปโunity-talk message
if it works I wouldn't worry so much about a better way to do it.. as
i would be about understanding exactly what you have so far..
you can refactor more when you learn more
i guess this is useful for looping thru vectors? lol cool, TIL
For Vector2:
- vector[0] โ vector.x
- vector[1] โ vector.y
For Vector3:
- vector[0] โ vector.x
- vector[1] โ vector.y
- vector[2] โ vector.z
Why? Just send it here
upload it
you should be able to..
if not use this
https://streamable.com/
ok gimme a sec
<div style="position:relative; width:100%; height:0px; padding-bottom:56.250%"><iframe allow="fullscreen" allowfullscreen height="100%" src="https://streamable.com/e/4lpgqs?" width="100%" style="border:none; width:100%; height:100%; position:absolute; left:0px; top:0px; overflow:hidden;"></iframe></div>
Watch this embedded Streamable video.
the link is all u need https://streamable.com/e/4lpgqs
Watch this embedded Streamable video.
mb
its soemthing to do w/ the UnitySelectionManager and the units in that collection
can you share the UnitySelectionManager script?
wait, 2021 was fine?
mhm upgraded most of my 2021 projects without issues, but I don't use many custom assets
Aha sorry, I think u r taling about seamless audio.
Line 128, you are trying to get the objects first child. If it has no children, that's an out of bounds exception
huh?
private void TriggerSelectionIndicator(GameObject unit, bool isVisible)
{
Debug.Log($"Unit: {unit.name}, Child Count: {unit.transform.childCount}");
if (unit.transform.childCount > 0)
{
GameObject child = unit.transform.GetChild(0).gameObject;
child.SetActive(isVisible);
}
else
{
Debug.LogWarning($"Unit {unit.name} has no children.");
}
}```
i think you should probably check if thers a child first before manipulating..
from the video tho it appears all ur selectable units have a selection image.. (as a child) soo idk it seems like maybe its adding stuff that isnt?
id open the UnitSelectionManager component and keep an eye on that list and make sure its working how u expect
how do i enable code recommendations for unity programming?
!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
โข :question: Other/None
thanks
Unity web build has issue for looping sound. it make pop or void sound every loop
https://www.youtube.com/watch?v=vAVi04mzeKk&ab_channel=SpawnCampGames
i have a tutorial on a top-down selection system.. maybe it might help to check my code and compare it to the one ur using.. (iirc i don't remember having that issue)..
i think the main difference I see is I don't add or remove units from the list from outside that class.. I tell the UnitSelectionManager which Unit it is.. and then it removes itself from the list..
bettt i will check but i have to go get something i will be back in like 40 min
that way its not trying to remove it more than once.. or trying to access something that isnt there
best of luck ๐
is it the actual sound clip? or we just assuming its webGL
how are you sure its the webgl / unity 6
sometimes pops arent easy to notice.. could be just teh very last sliver of the audio file..
if u have some sort of audio editing tool you can shorten it or clip the end/beginning and see if the pop goes away.. or test w/ another clip
Ok but I asked for both the exception and the last log message
Remember I asked you to log the gameobject and the childcount until the exception is thrown
At this point it's just all assumptions until you start debugging
And now people like @rocky canyon will suggest the exact same thing because conversations have 40 minute intervals, after which we just start over again
So please pay attention and give us results if you want this to be fixed
thanks! this is really helpful!
well, enjoy the delay.. he'll be back later ๐
Yes, exactly ๐ฎโ๐จ
np ๐
webgl ( unity 2022 ) and web (unity 6), all have issue
its probably not the editor then, I use webgl without issue
because i built to webgl in 2022, also built in unity 6 to web
what browser did u test?, editor has no issue
on editor everything is ok
firefox
only webgl build has issue
Can you share import setting of audio?
And how did u loop? just set loop = true?
they're the default ones , I havent touched them usually
did u test on chrome?
yes on the audiosource
yes
hm then code is same to me
did YOU try a different browser
and where did you host it? which settings you exported with ? etc..
like this?
I think so, but i'll test it again
yes the code would not be the cause, its probably some wrong format you might have selected
localhost and also other hosting has same issue
aha. i'm using wav format and you?
thats not what I meant, inside of unity and the export page of webgl
public void Build()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Vector3 targetPosition = ray.origin + ray.direction * range;
Collider buildingCollider = currentBuilding.GetComponent<Collider>();
if (buildingCollider != null)
{
buildingCollider.isTrigger = true;
}
Renderer buildingRenderer = currentBuilding.GetComponent<Renderer>();
Vector3 boxSize = buildingRenderer.bounds.size / 2;
Vector3 boxCenter = targetPosition;
Quaternion boxRotation = currentBuilding.transform.rotation;
Collider[] hitColliders = Physics.OverlapBox(boxCenter, boxSize, boxRotation);
bool canPlace = true;
foreach (Collider hit in hitColliders)
{
if (hit.gameObject != currentBuilding)
{
canPlace = false;
break;
}
}
currentBuilding.transform.position = targetPosition;
Renderer renderer = currentBuilding.GetComponent<Renderer>();
if (canPlace)
{
renderer.material.color = Color.green;
}
else
{
renderer.material.color = Color.red;
}
if (isBuilding && canPlace && Input.GetMouseButtonDown(0))
{
isBuilding = false;
currentBuilding = null;
if (buildingCollider != null)
{
buildingCollider.isTrigger = false;
}
}
else if (!canPlace && Input.GetMouseButtonDown(0))
{
Debug.Log("Cannot place the building here!");
}
}
So when the building is a floor it should snap to other floor. but not when the player is looking at a floor. How can I manage to do that?
hm. but if we are using same unity editor version. there is nothing to touch about it?
Is there any option for it?
And this is my import setting
did you test blank project? different settings? different browser etc. You have to do more testing to isolate the problem. Also send a link of your webgl maybe its just your end
oh i dont remember i test on blank project. I should try.
by the way which version of unity are u using?
I use both 2022 and 6
are u using SRP? (universal )
oh
then i'll try to SRP for isolate testing
ah before it
i want to share my issue video
I just tought it was ok but later found issue
here is my video
you can check it have something pop sound
or something void(empty) sound
this was not happen on ur?
can i somehow set only 1 coordinate in vector3 without creating new? if no, just say no
I post all associated forum
web, audio
thats crossposting, don't do that #๐โcode-of-conduct
sometimes, it depends if the Vector3 is a field or a property
ok
also firebox has same issue
ok, thx
Geussss we Back
whos back
the one and only
erm what the sigma
Sigmas Back
I suggest you to start a thread about your issue next time, whenever your problem takes time to be solved, or whenever you know you'll need to do other things that will make you unable to check this channel
Ok mr how do i aquire a thread
Mr sigma created a thread for us
Mr Sigma created a thread for uss
unit.transform.childCount
i did not get the debug
We answered that already
Show a screenshot of your full console, including the buttons for hiding message types
hi, im making a top down rpg game similar to that of undertale. what is an efficient/effective way to manage/save/set a lot of bools to check if the player did some sort of action and change character dialogue according to the value of those bools? (i.e, a player chose to insult a character, next time they open the game the character is still bitter about them being insulted)
Oh hey look 8 hidden logs
c#'s bitarray mb?
๐โโ๏ธ tamam ehehe samanana eh eh
this seems close to what im looking for, thank you! ^ ^
but if u use it u can't manage it in editor without crutches. but u can just make some object on scene with script with a lot of bools static & basic & a huge onValidate()
so what must i do so i can continue on the coding adventure of mine
๐คฉ
Don't try to get the first child of an object with none
tip: define constants for indexes, just numbers makes code unreadable
erm like put it in googo gaga for me please
I just did
how do i do that
sorry, could you explain further on what you mean by constants?
for example, did u use GameObject.CreatePrimitive()?
hello you still there home boy
i dont wait if daddy aint comeing home you know
@solar torrent Can you settle down. Stop pestering people.
you're not waiting, waiting does not include sending lots of messages ๐
if yes, PrimitiveType is enum where every element is like number, co u can create cube by GameObject.CreatePrimitive(PrimitiveType.Cube) instead of GameObject.CreatePrimitive(3). what is 3 - u can only ask it to spirits
with your extensive knowlodge will you be able to lend a hand
what help do u need?
how/when would i use CreatePrimitive() for the bitarray though?
no way, it's just example for constants for more readablecode
ohh okay, my bad i got a bit confused ๐ญ (thanks for the help btw! ^ ^)
what r u doing? & what are these numbers?
thats what I'm sayingggg brooo๐ข
hello guys i have a question, how to save that ?
i dont know why but i cant use zqsd
idk go to adavanced
this is a code channel, and that's not a code question. Just do File -> save
@solar torrent This is your last warning before you're muted, to stop being annoying. Also, if you're going to continually spam this channel with noise, make a thread instead.
bro i made a thread
Use it, then.
no one saying anything on it though
can u just send the code that results in it?
bebuska I'm russian
๐โโ๏ธ
bebuska?
hell yea
!mute 793466504309768195 1d You can come back tomorrow. Be less noisy, actually help people help you with explaining things, and stop expecting people to hold your hand with your issue.
noobie_q was muted.
Sorry this is bit VS focused, but I can not see how to turn off the 'fade' effect when code is unused because its really annoying actually and I only remember the 3 dots effect. If i am in the middle of writing a class there may be unused functions - I do nto need the text to be faded!
Hi everyone I am trying to set a simple navigation to the sphere as shown in the screenshot, however I am getting a SetDestination" can only be called on an active agent that has been placed on a NavMesh. error despite my best attempts to adjust the sphere. Thoughts?
As far as can be seen in your screenshot the baked navmesh is only on the white ramp area, nowhere near your sphere
I readjusted the nav mesh, but no dice
where is the gizmo of navmesh agent
Is that what you are referring to?
this feller
press F and zoom in your ball thingy more
Hi
navmesh agent component is on this sphere ? whats the scale of the sphere
.5 .5 .5
This is another MS bug in latest version - they really dropped the ball... https://developercommunity.visualstudio.com/t/Fade-out-unused-methods-is-now-being-for/10790208?q=fade+out+unused+function
how big is the navmesh agent sizes
Radius 0.5
Height 1
Step Height 0.4
this is just for baking not the actual navmesh Agent
Are you referring to this Navigation panel?
yes but this not just monobehaviours - it fades out any unused function now - anyway VS is a pain today!
thats not an agent no, those are for creating templates of agents
Oh I see
hadn't noticed
Here's the navmesh Agent for the enemy
There's no navmesh Agent for the destination, is that the problem?
hard to tell from this prospective but make sure its not too far away from the blue ground
and no the destination does not need an agent ofc, its not a moving agent lol
put the enemy closer to the ramp
you should probably use navmesh surfaces btw, this way of baking is deprecated
Oh I see
Yes lol
Hmm, I'll re-review the video I'm following and see if I missed a step. For future projects I'll use navmesh surfaces
yeah they're much better because you dont have to painfully go through each gameobject to mark as navigation object and all that
Ahh makes sense, thank you for the guidance
if/when you come back with further questions on the navmesh .. use #๐ปโunity-talk - it's not a code question
is it working now btw @dense root
Guys how can i make an image grey then make the grey go away from top to bottom in x seconds?
probably shader
or do you mean UI image
that would be easier
I'm trying to get the player to read a float from an xml file. This system works, but only for non-float falues, as of right now. What can I do to get this working, without changing the xml file?
Player class --> https://hastebin.com/share/wafonifule.csharp
Defaults (DefaultJrlGameObject class) --> https://hastebin.com/share/amomadeniz.csharp
MovementVariants.xml
<MovementVariants>
<HorizontalMoveAccel>0.2</HorizontalMoveAccel>
<WalkSpeed>5</WalkSpeed>
</MovementVariants>
Error: FormatException: Input string was not in a correct format.
Yeah I got the navmesh to work however I'm now having trouble with the player controls. For some reason I'm getting an "The associated script can not be loaded." error but there don't appear to be compilation errors in the console.
yes please
try go to top, assets -> reimport
kk
just put another gray image over it then scale it the direction you want, should be easy once you set pivot to top edge
Weird I'm getting the same error
restart the editor?
I clicked reimport all and it restarted it, I can try again
another reason you should probably be using lts
Yeah, I think I'll upgrade the project and spend some more time with it after a break. Thank you so much
btw if you have a blank square you can set the image mode to filled and you can just use the slider so you dont have to worry about scaling anything or changing pivots
Okok I'll try that ty ๐
just need to change the slider value through code
Oh that simple? Okok ty
hey there! i'm here to ask for help again so i wrote some code to spawn pipes in a flappy bird project for my first project which worked before dinner but then i came back after and now suddenly it won't run anymore and i get a ton of errors. for exmaple the gameobject.findgameobject which worked fine before doesn't work now
does anyone have a idea what i did wrong for all this stuff to stop working? i get the same error for the Time.deltatime, instantie, vector3, transform, random and a vew more
well yeah you have a syntax error
always start at the very top
look carefully
oh lord
i see it now...
it was the using+! thank you so much!
i've spend the last 20 minutes looking at it and not getting what was wrong while it was the top row all along
yeah usually its the line above and it cascades down from there
Haha I've done that couple times hit a button on side of my mouse when i go back to desk and puts a character into script ><
Hi! I'm following tutorials and using many other resources to mane a "first draft" while learning. Trying to make a 2d side scroller character jump, but it doesn't seem to want to do that no matter what I do...
Here's the code that I've got so far:
using UnityEngine;
using UnityEngine.Assertions.Must;
public class playerMovementNew : MonoBehaviour
{
public float moveSpeed = 10f;
public float jumpForce = 5f;
public Rigidbody2D rb;
public SpriteRenderer SpriteRenderer;
public Vector2 movement;
private void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
//movement.y = Input.GetAxisRaw("Vertical");
if (Input.GetButtonDown("Jump"))
{
Debug.Log("Jump button pressed.");
rb.AddForce(Vector2.up * jumpForce, ForceMode2D.Impulse);
}
}
private void FixedUpdate()
{
rb.MovePosition(rb.position + movement * moveSpeed * Time.fixedDeltaTime);
// ^Makes player actually move based on input.
if (Input.GetAxisRaw("Horizontal") < 0)
{
SpriteRenderer.flipX = true;
}
else if (Input.GetAxisRaw("Horizontal") > 0) {
{
SpriteRenderer.flipX = false;
}
}
//^Makes the sprite flip directionally
}
}
Any idea what's wrong here? I press space and the debug says I did, but the character doesn't go up.
did you set the jump force in the inspector to something else?
I've been trying to mess around with it. Whether it's 5, 15 or 10000 it doesn't matter
(sidenote, comments that annotate code usually go before the relevant code, so you get an explanation before having to read the code)
So in this case which one should I replace? rb.MovePosition or the AddForce one?
you could replace MovePosition with setting the x velocity
Vector2 vel = rb.velocity;
vel.x = /* intended x velocity (NOT proportional to deltaTime, since velocity is already per unit time) */;
rb.velocity = vel;
so the velocity would bemovement.x * moveSpeed
(if it's a sidescroller, not sure what you'd need a vertical axis control for)
I'm sort of following different guides to get a grasp. I've thrown the vertical one in a comment so that it's not actually used, b ut left it there for myself as a reference while I'm learning. It's day 3 of me learning this so far XD
i'd recommend you stick to a single, reputable guide, since different people have different styles and it's likely you'll encounter slightly different ways of doing stuff in different tutorials
!learn
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
using UnityEngine;
public class Movement : MonoBehaviour
{
public float speed = 5f;
public Rigidbody2D rb;
public Camera cam;
public Animator robotAnimator;
private Vector2 movement;
private Vector2 mousePos;
private bool isMoving;
private bool isSprinting;
void Update()
{
movement.x = Input.GetAxisRaw("Horizontal");
movement.y = Input.GetAxisRaw("Vertical");
mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
isMoving = Mathf.Abs(movement.x) > 0 || Mathf.Abs(movement.y) > 0;
isSprinting = Input.GetKey(KeyCode.LeftShift);
AnimationStuff();
}
void AnimationStuff()
{
if (isMoving)
{
if (isSprinting)
robotAnimator.Play("Run");
else
robotAnimator.Play("Walk");
}
else
{
robotAnimator.Play("Idle");
}
}
private void FixedUpdate()
{
Vector2 newPosition = rb.position + movement * speed * Time.fixedDeltaTime;
rb.MovePosition(newPosition);
Vector2 lookDir = mousePos - rb.position;
float angle = Mathf.Atan2(lookDir.y, lookDir.x) * Mathf.Rad2Deg - 90f;
rb.rotation = angle;
}
}
``` Does anyone know why the animations aren't playing/Why the "isMoving" bool doesn't detect movement. (Please don't be mean I'm a beginner)
try debugging some values. is movement being set? is isMoving being set?
What do you mean "being set"
being assigned to correctly
And how exactly would I check that with the debug.log?
you log the value out
and you see if the result is what you expect
just, Debug.Log(movement);, same for other variables
And the reason your animations aren't playing is because you are starting them every frame
How can I fix that?
stop doing it
Okay, the "isMoving" bool does not become true even when the player is moving, but the movement vector does exactly what it's supposed to.
How should I make the animations start then?
it's not about not making them start, you are already doing that, it's about not doing it too often so apply some logic
So because it is checking it every frame then they cannot play, but how can I make unity check if anything is happening without the function being inside of update?
maybe restrict calling AnimationStuff unless certain conditions are met?
So an if statement, but what should it be?
made a script that has 4 drop zones and 1 general card to drop onto. Worked perfectly fine until I wanted to make the card bigger once dropped (changing the size to droppedSize). Problem is line 50 makes the card go back to the place where the card is picked from (startPosition). Chat gpt didn't really help
using UnityEngine;
using System.Collections;
public class DragDrop : MonoBehaviour
{
private bool isDragging = false;
private GameObject currentDropZone;
private Vector2 startPosition;
public Vector2 droppedSize = new Vector2(335, 522);
void Update()
{
if (isDragging)
{
transform.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("DropZone"))
{
currentDropZone = collision.gameObject;
}
}
private void OnCollisionExit2D(Collision2D collision)
{
if (collision.gameObject == currentDropZone)
{
currentDropZone = null;
}
}
public void StartDragging()
{
startPosition = transform.position;
isDragging = true;
}
public void EndDragging()
{
isDragging = false;
if (currentDropZone != null)
{
transform.position = currentDropZone.transform.position;
RectTransform rectTransform = GetComponent<RectTransform>();
rectTransform.sizeDelta = droppedSize; //problem is here
}
else
{
transform.position = startPosition;
}
}
}
if the card always goes back to startPosition it means
else
{
transform.position = startPosition;
}```
this block is always running.. which means ` if (currentDropZone != null)` is always false.
but it's the endragging event, should't it run only when I drop the card?
if I remove the
rectTransform.sizeDelta = droppedSize;
it works fine
but it's the thing I want, to resize the card once dropped
i cant see how that would have anything to do with the positioning whether its present in the code or not ๐ค
does that line cause any errors in the console or is this just a
"working, but not desired outcome" type of problem?
not even working, it doesn't even resize the card, it just make it go back to the default position
it's the same script but modified to wait a second before doing that line, but it does this
well for starters to position UI element you use
rectTransform.anchoredPosition;
that might be the root cause of ur issue
if (currentDropZone != null)
{ //grab components
RectTransform rectTransform = GetComponent<RectTransform>();
RectTransform dropZoneRect = currentDropZone.GetComponent<RectTransform>();
// set position to match dropzone position
rectTransform.anchoredPosition = dropZoneRect.anchoredPosition;
//optional assignments
rectTransform.anchorMin = new Vector2(0.5f, 0.5f);
rectTransform.anchorMax = new Vector2(0.5f, 0.5f);
rectTransform.pivot = new Vector2(0.5f, 0.5f);
// set size
rectTransform.sizeDelta = droppedSize;
}```
screen space coordinate system vs world space coordinate system
that said and all.. But chosing to use UI for a 2D type of game probably isn't your best choice.. (not sure how much you've already built)
but Unity UI usually isn't the most performant.. and is meant to be used more so to display stuff(info) to you..
as for interacting w/ the objects I'd probably chose to use 2D Sprites.. those will exist in world-space and will be much easier to drag, drop, and interact with..
even if they're "text heavy" you could pair 2d sprites w/ textmeshpro world text objects
either way.. the .rectTransform.anchoredPosition is the bit that will fix what you already have..
if u go w/ 2d sprites instead you can resort back to the basic transform.position = thatPosition; type positioning
it does work.. maybe not w/ your setup for some reason
public void TopLeft()
{
thisRect.anchoredPosition = topLeft.anchoredPosition;
}``` etc, same for each of the test methods i call in the clip
for yours, not sure, I'd probably suggest:
make sure your components are assigned.. (like the recttransform you grab w/ your getcomponent methods)
can debug them afterwards to see that they're assigned ` Debug.Log(rectTransform.name);`
make sure you're setting its `anchoredPosition` debug it afterwards see if it has a value that makes sense `Debug.Log(rectTransform.anchoredPosition);`
put some debugs in ur if statements make sure they're being called like you expect
`Debug.Log("If statement is true, doing this"):`, same w/ else, or false, or w/e
nothing more comes to mind besides something i'm just not seeing.. or some error you haven't revealed yet
the logs and stuff should tell you whether its an issue w/ ur logic flow
or its a problem w/ assigning the wrong values or variables
With the line removed works just fine, now i get that adaptive performance thing after I used ur code and removed it
the one with the rigidbody is the card
you should not mix phyiscs with UI / canvas btw
I used a tutorial for the base of the game
I mean that doesn't mean its correct
I know but i dont want to take the just redo the game in another style way yet since not much is left to do
another style?
Not using only canvas
if you plan on using colliders/physics then you'd switch it to using sprites,
if you use canvas then you have to use the event system instead with all the functions that come with
the canvas and the physics objects are not even in the same space
I need help with my pathfinding algorithm, I'll record a little clip to show whats wrong but essentially i can only pathfind around certain like... obstacles
its a little hard to explain but i was working on it for multiple hours yesterday and im launching the project rn
well, nvm, chat gpt made it work somehow, thanks for help @rich adder @rocky canyon
Hi, i been thinking, how i can make the sprite of the character of a 2D game flip depending on where the mouse is?
my pathfinder gets stuck here
tho it can pathfind around other structures of blocked cells
i mean, if the mouse is on the left of the player, the player's sprite would flip to make it face left
there are some cases where it cant pathfind around certain cells
it perfectly pathfinds around this structure of blocked cells
its an image so you cant actually see it get to the destination, but it does
and it gets to the destination no matter where it starts with this structure and many others
there are just edge cases where it cannot
i know the code is definitely terrible, this is just a prototype keep that in mind
thats why i said earlier "Im not sure how much you've done".. it might not make sense to change it.. but instead just power thru it
The easiest approach would likely be to change the x scale to negative
theres usually two options..
"scale the object negatively (this works out well most times b/c the axis will flip w/ it"
or you can flip the sprite FlipX (this means you need two states of movement.. when lookin left, if lookin right
No, i mean. What about the spriterendered?
But my issue is how i can detect thr mouse
what about the sprite renderer?
nah, its a completely acceptable option..
are you trying to detect which side of the player the mouse is or something?
Yep
but note that the axis will not flip around.. (ur transform.right) (y axis in 2d) will always point right..
if u scale the object negatively.. then the axis will flip so looking right will have the axis pointing right.
and looking left will have it left
if its just for the appearance flipping the sprite should be fine
you can use Dot product for that
How?
i must suck at programming
positive value would be on the right side.. and negative value would mean its on the left
i know what it does ive jst never used it in this application
Dot Product can be thought of as a "Sameness" value of two direction vectors. If it's 1, then both vectors are pointing in the same direction. -1 is opposite, 0 is perpendicular.
Ok. But i mean, now i can detect the left and side of the mouse...but how i can detect the mouse itself?
like its position?
Yep
Camera.ScreenToWorldPoint(Input.mousePosition) i think
or something like that
to get its world pos
If you want to know where the mouse is in the world, you'll want to raycast from the camera to the world
https://docs.unity3d.com/Manual/CameraRays.html
So how the script would look like?
Oh.....
Ok
itd be like this i think
Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
mousePos.z = 0;
to get the world position of the mouse
Although if it's 2D, ScreenToWorldPoint should be fine
You only really need to worry about the ray for a perspective camera
If you just need left/right and don't care about any other directions, you can just check if that result is less than or greater than the player's X position
(URP) I'm trying to add a flashing to my game, but it doesn't go nearly far enough to see what's in front of you. Turning up the intensity of the flashlight makes it still not go far enough, and flash the player when looking at something too close. I can't seem to find a way to make the flashlight see further and also be darker up close. Is there a fix to this? (first image intensity 3, second image intensity 30)
Thanks :3
algud
a build of my pathfinder if anyone wanted to test it, it works sometimes around obstacles
The red cell is the pathfinder, the green cell is the destination
Press Tab to show the neighbours around the pathfinder in blue
Press Space to pause and unpause
Left Click to make any cell an obstacle
Right Click to make any obstacle a regular cell
What are you using now? A spot light?
Btw, this is not really a code question
sry my bad
im using a spot light
Technically, this is how a spot light would work in real life. Since PBR rendering tries to mimic real life behaviour, this is how it looks by default. How exactly do you want it to look?
I'm trying to go for a flashlight that is far reaching, but not super bright up close. I want to be able to see where I am going in my map, but currently the light is too bright for that. My game is a speed parkour game and running into walls is pretty annoying. I originally had the whole map have a light cast on it so you could see, but it looked terrible. I'm making a flashlight mostly for ambience. End goal is just to tone down the light up close.
You might need some kind of custom light implementation for that I think.
Ah okay, I'll look in to how to make something like that. Thank you for the help.
do i need to put -1 after .Count in a list?
like
if (list.Count - 1 < value)
or does this work fine
if (list.Count < value)
is there a version of Mathf.Clamp for Vecotr 2?
I know theres ClampMagnitude but that only does a maximum, not a mimimum
cause i have a vector that i dont want to go below zero, do i have to just Mathf.Clamp X an Y seperatly?
i think you have to do it seperately
this
for enemy ai, would a breadcrumb solution suffice? like the player drops a "breadcrumb" every certain interval and if the enemy has los of a breadcrumb it moves towards that breadcrumb
sure if you want it to follow the last players position, I would just use the conventional A* for AI enemies though
i thought a breadcrumb solution would be good because
i dont want the enemy to always know where the player is after seeing it, with breadcrumbs if the enemy loses los of the player it can just move to whatever breadcrumb is in los and if it can see the player when it gets to that breadcrumb then great else it can be idle
ive tried A*
its nice but not what i need
a* and this breadcrumb idea are not mutually exclusive. I do this in one of my projects and use navmesh (which uses a*) to move the enemy
does navmesh work in 2d?
oh
There's a GitHub package you can find that allows you to use it in 2d,but the algorithm is fairly easy to implement yourself
ill check these options out
ill go through them and see which one is good for me
A* probably will be better, in the past it just didnt really work out
A* is probably the best pathfinding algorithm unless you need hundreds of objects pathfinding to a certain position, if that's the case use flow fields
im making a dialogue system with a tutorial (cause i dont know how to make one) so for now im doing the dialogue in the console cause i wanted to start with that but i get a error whenever i start the dialogue i get a error how do i fix this? (https://www.youtube.com/watch?v=_nRzoTzeyxU&t=452s)
(i didnt finish the tutorial yet but it works in the video so i just wanna fix it)
!code this isnt readable as is
but you should also show the specific error you get. you likely missed a step, or havent gotten to the part of fixing the error. not many people will watch through a video and try to compare it to your 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.
wait so this is weird cause now when i play test i get no errors
and it actually works
(yes the script was saved when i was getting errors)
(and i didnt change the scripts)
guys is it possible to check if an animator has a specific boolean?
Could I get some help regarding raycasts in 2D please?
I am having trouble getting the raycast to detect my player and return a RaycastHit2D. I have given the required parameters as seen below.
RaycastHit2D los = Physics2D.Raycast(m_mob.transform.position, (collider.transform.position - m_mob.transform.position).normalized, m_visionRadius, m_targetLayers);
Debug.DrawRay(m_mob.transform.position, (collider.transform.position - m_mob.transform.position).normalized, Color.red, 0.1f);
I also drew rays to make sure it is actually looking at all colliders within the specified radius that belong to the Player layer as seen here
Collider2D[] targetColliders = Physics2D.OverlapCircleAll(m_mob.transform.position, m_visionRadius, m_targetLayers);
So far the colliders and debug rays are correct, they point at every collider belonging to the Player layer, however, the raycast isnt working as expected.
I have provided it the correct vector values since the debug ray works fine and takes in the same values, however it doesn't seem to return anything from the method, its always null.
It uses the same values as my OverlapCircleAll arguments but it doesn't return anything despite being in direct line of sight.
- I have read the docs many times over and I don't know what I'm doing wrong.
- Also, how do I specify a layer with colliders the block line of sight in addition to the layer I wish to detect the collider using the raycast from?
Hi I just started using unity and for some reason I am having trouble making my character jump
But when I put the jumping script on a cube it jumps so I'm a bit confused why it doesn't work on my model..
RaycastHit2D is a struct, it can't be null. Anyway, go through the checklist here: https://unity.huh.how/physics-queries
Odd that my Autos displayed null values thenโฆ
What are Autos and when do you initialize/assign them? I'm assuming Auto isn't a raycast hit 2d.
When you attach the debugger to unity and hit a breakpoint you can view Autos that display current local variables and their data within
Show the data. You may be looking at the wrong thing.
Spot the difference
i dont understand
which variable do you want to pass to the method?
nevermind i fixed the error
yes, sentence is not the same as Sentence. Case matters in C#
in most languages I think
not at all, usually only languages with a C base
there are probably many, many languages you have never even heard of
probably ๐คฃ
definitely
Whats the difference between Vector3.Distance and calculating manhatten distance?
can someone help me out with this movement script i made i would like the movement to be a bit smoother
Define smooth
I'm assuming you'd want velocity to gradually increase towards the target instead of becoming the value immediately
i would like to jump while i m running
the way your coding your movement doesnt allow for that
oh
Sounds like you're needing more than just a simple fix
youd have to refactor that bit of movement code
ok
i think you need like a movedirection vector3 or something, im not good at 3d but i just know that movement code doesnt allow for jumping and running simultaneously
Hi, i'm new to unity and i saw a tutorial on how to do better jumping and i want to integrate it to my project, any ideas on how to implement it for the "newer Input System" (the one that gives you OnJump(), OnRun(), etc) ? Thanks in advance
ok so would this code work ;
possibly? again im not a 3d coder so im not sure what the right way would be
ok thnk u tho
do anyone know where can I look for documentation on how to do a 2D grid pathfinding system in a 3D world, in which entities don't get inside other entities?
rigidbody, you could also just use a character controller and emit a light force around each unit so they don't occupy each other
if you don't need to implement the whole thing yourself, I can recommend A* Pathfinding Project
the free version should be enough for your needs
Vector3 velocity = rb.linearVelocity;
if (...)
velocity += forward;
if (...)
velocity += backwards;
if (...)
velocity += right;
if (...)
velocity += left;
velocity.x = Mathf.Clamp(velocity.x, min, max);
rb.linearVelocity = velocity;
if (canJump)
rb.AddForce(jump, ForceMode.Impulse);```Where you'd substitute the variables above with their respected values. Consider multiplying directionally increments by delta time (jump should not be multiplied by time).
ok thank you
I need to implement it myself since I need it to be very specific. Basically I need it to work like in Shop Titans, in which the movement is exclusively grid based with diagonals and also the entities avoid themselves
instead of all of those if statements, consider using a movedirection such as
x = Input.getaxis("Horizontal");
y = Input.getaxis("Vertical");
Movedirection = transform.forward * y + transform.right * x;
Rb.LinearVelocity += Movedirection * movespeed;
//100% clamp and do other things
this is obviously a rough draft but it should work
not sure how it works in Shop Titans, but this implementation is extremely robust, works perfectly with grids and has builtin avoidance features
if you really want to implement it yourself, then you should look into the A* algorithm for pathfinding, then during the path calculations you can choose to avoid other entities
you'll also need to create the pathfinding grid somehow
I would as well just modify the Y value for the rb velocity to make a jump anyway, or use forces for movement
Had something like that originally but without the assignments above and thought it would confuse the dude thus edited it to correlate to their original design
yeah it does look a little more confusing to beginners but it is always good to teach them new things
also you could substitute the old input system for the new one, I just do not know how to use the new one ๐
in pathfinding should i use manhattan distance or regular Vector3.Distance?
Manhattan (as it works for grids) if you are using A*
i searched it up and apparently manhattan distance isnt good for diagonal movement
and stuff
huh?
why would it be bad for diagonal movement
it just makes the distance between the current node and the top/down , right/left/down/up movments a distance of 2
now if you want the distance to be 1.4 for diagonal movement just use the โ2
which is somewhere around 1.4
would that benefit?
I've never tried it
but I'm guessing it will be roughly the same, you can google the differences if you would like
i cant get past this
and obstacles placed like it
but most other setups work fine
are all of the Fcosts correct? are you checking all of the neighbors around the current node?
are you ignoring the current node?
yeah, you cant see it because its an image but the pathfinder just continuously moves between 2 nodes
so it does pathfind?
to something
just not to the right place
and it works fine with no obstacles and when obstacles are placed in certain ways
i can see which cells have the lowest fcost, the cell i have selected apparently has the least fcost
and now this cell i have selected has the lowest fcost
and the pathfinder continuously moves between these cells
are you checking end to start or start to end
what?
the current node on start of the project should be the starting node I believe
yep
then you pathfind to the end node, then retrace steps (to get the path)
oh im not doing it that way
even ill admit i have no idea what im doing imo
what ive done has gotten me this far
yep that will be my approach, I already did it in godot. So I will try to do the same here, which is to basically calculate the path on every step you do on the grid, avoiding any obstacles (other agents are also obstacles)
basically i just move to whichever neighboring cell has the least fcost
and on every step you will change the grid position you are in as an obstacle, and when that agent gets out of it, you make it available again
are you checking for obstacles?
I'm guessing you are which is good
yeah, the list of neighboring cells i get doesnt include obstacle cells
Sebastian league has some good stuff on A* pathfinding, some good information that you can use
it only includes valid cells
i looked at that, i wanted to try doing the code mostly myself whilst having an idea on how it should work
i watched his introduction video
in theory i think the way im doing it should be working
idk why it isnt
god its 2am and ive been working on this for 2 days
๐ญ
this isnt worth it im going to sleep
fr im bad at coding ๐ญ
coding requires good rest, I would suggest looking at the algorithm in depth to see what you need and what you do not need, you can also look at articles and examples on it as well (which I would recommend)
I'm swapping back from Rider to Visual Studio code since I might not get another Rider License for next year.
With that being said, I need to reinstall Visual Studio's extensions, and as such, which extensions in Visual Studio code is recommended for a game developer?
All you need is the Unity extension. https://on.unity.com/vscode
My intellisense is not picking up serialized field
Follow the instructions on that link
does anyone know what stuff do i need to do to make a boomerang?
i can picture what i want, but i dont know how to name stuff so idk how to look for it in the internet
If we're talking like 2D zelda boomerang you're just moving a transform and giving it some collider
break down the process of what a boomerang does:
- press a button
- move boomerang a certain distance
- check if distance is reached
- move boomerang back to starting position . . .
creating a mechanic or system is all about logic (coding in general). once you know/understand the logic, you substitute the logic with its programming counterpart . . .
If you want curving, you can create a path using AnimationCurve but I'm pretty sure Zelda was just a straight forward throw and return
3D versions had more realism to them
if it's like a terraria boomerang make sure it's going towards the player instead of the starting position after the apex
you could also use acceleration instead of a distance check
Does anyone know how to get a random entery form a dictionary? To be more specific this my Code ```cs
public Dictionary<Vector2,TileScript> SpawnTilesDic;
public void AddEntery() {
SpawnTilesDic[new Vector2(x, y)] = currentTile;
}
public void ReadEntery/SpawnBox() {
TileScript spawnTile = SpawnTilesDic.Random(); //Does not work
}
have you tried googling for it at all?
https://stackoverflow.com/questions/1028136/random-entry-from-dictionary there's ElementAt, Values, Keys
yeah a read that, but don't understand it
what is there not to understand?
get a random number between 0 and the number of entries in the dictionary
get the value at that element number
I'm sorry, i found it really difficult to warp my head around it. Even this simple task took me now nearly 30 mins. But i have, so thanks
hello unity heads, im having some trouble with a coroutine
I am making an arcade racer. At the start of the race, I use an Ienumerator to countdown to the race start, this works fine. I want the player to be able to quickly restart the race, so I would like to run the coroutine again, however the countdown somehow end up as a negative number?
because you haven't reset the number at the start of the countdown
I have done this
not properly, otherwise it wouldn't go negative
{
//reset collectibles
currentCollectibles = 0;
UpdateCollectibleCount();
hasAllCollectibles = false;
// set vars so that the player can reset with R key after finishing
raceStart = false;
raceEnd = false;
// turn off end screen
EndRaceBackground.SetActive(false);
LeaderboardBackground.SetActive(false);
NavigationBackground.SetActive(false);
//reset race timer and countdown to start
timerTime = 0;
countinTimer = 3;
StartCoroutine(CountdownToStart());
}
This is the reset race method
the countdown definitely does go back up to 3, but it counts down twice as fast
ok.. show the rest..
how about stoping the first coroutine
If I keep resetting it, it always back to 3 straight away and then instantly jumps to a negative number
IEnumerator CountdownToStart()
{
while (countinTimer > 0)
{
countinTimerStarted = true;
yield return new WaitForSeconds(1f);
countinTimer--;
}
countinTimerStarted = false;
}
This might the problem because Im new to using them and unsure
well if you restart you would have to stop the current coroutine
you shouldn't need a stopcoroutine, you should be exiting it properly when the countdown finishes
should you not be setting countinTimerStarted = true; somewhere?
That was my assumption but im learly wrong somewhere
Inside the coroutine
its there
no it's not
you are blind
that bool doesn't look like it does anything anyway - probably used elsewhere
(it should probably be before the loop?)
Its referenced by other methods doing different tasks, such as UI display only for the duration of the countdown
if you are expecting your coroutine to do something, should it not call something after the while loop has finished
Im only using it to display the countdown on screen
and not to control the actual start?
I display "countInTime" at the race start
Correct
so how are you controlling the actual start
Im not sure what you mean
oh right
if (countinTimer > 0)
{
raceStart = false;
countdownText.gameObject.SetActive(true);
countdownText.text = countinTimer.ToString();
countdownBackground.SetActive(true);
}
else
{
raceStart = true;
countdownText.gameObject.SetActive(false);
countdownBackground.SetActive(false);
}
how are you controlling them not to start before the countdown is over
This is in the update method
They can do some actions for the race start so I dont completely disable the player, just some things
ok think about that, that's kinda starting/stopping it every frame
that works, but it doesn't really make sense
Yeah its inefficient
But its not the cause of my current problem
I can make it pretty later
(it's probably not related to the current issue, but that may cause issues with having like, a proper, understandable logic flow in the future)
Yeah thank you, ill take that on board
this
yield return new WaitForSeconds(1f);
should probably be WaitForSecondsRealtime
Okay, why is that?
WaitForSeconds is scaled according to Time.timeScale
because WaitForSeconds is frame rate dependent
I have changed it and the problem still occurs
have you tried debugging the coroutine? seems like it should exit on its own just fine
Im not sure how I would go about this
debug.log
just, Debug.Log in the loop, Debug.Log after the loop
Okay, sounds good
I have been printing the countInTimer to the console
looks like this on the right
check also how many coroutines you running
if(countinTimerStarted) return; StartCoroutine(CountdownToStart());
No
So it looks like when i start the coroutine on reset, it never stops
the first instane does
instance
how are you calling Restart?
pressing the "r" key on my keyboard, and also from the end screen and options menu
i have an event manager handling it
in code
yes
oh i see lol
"What time is it?"
"It's Thursday 5th"
more like
"how are you checking your engine oil"
"only when the engine light is on"
// quick reset scene with R key
if (Input.GetAxis("Reset") > 0)
{
EventManager.RestartCurrentScene();
}
In the gamemmode controller
in Update?
yeah
Lmao
yeah you're starting a coroutine every frame that R is held down
shit
that figures
called it ๐
thanks guys
and the decrement happens before the check, so they're all decrementing
also you have a bool. use it. Never hurts to assure yourself
if(countinTimerStarted) return; StartCoroutine(CountdownToStart());
also edge case to test while you're at it: what happens if you press R while the countdown is active?
I dont let the player restart when countinstarted is true
Hello, I am pretty new to Unity, I have a slider and this function:
{
bloom.intensity.value = brightness;
}```
But for some reason, in "On Value Changed" there's that 0 and the value of "brightness" doesn't change at all. I maybe don't understand how sliders work as I am new, so I would be very grateful if someone could explain to me!
Oh perfect, that was it haha thanks!
can someone help me get this pause menu working i want when player presses escape this to pop up and the player should not be able to move nor anything else the game should pause and the buttons should work ๐
what exactly is the issue? that the player can move, or that the buttons aren't working?
or have you not implemented it at all? in that case, have you tried googling how to make one?
i used multiple scripts when i press escape it shows it but the game is not paused i can still move and cant press the buttons
have you written anything to make it actually paused?
i cant code i just use any script i can find
then start with the beginner c# courses pinned in this channel
Hi am am a beginner with coding and I am having a problem with my code if someone can dm me and help ty๐
we don't do dm support here
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #๐โfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
I see ok so I have a 2d game where when you hit the zombie he dies but the problem I am having is or the game object dies so I made him go invisible but I can figure out how to make it go back to visible
why do you need to make it visible again
It's like a infinite but I tried killing it but then the game breaks and doesn't create new ones so I made it invisible but the new ones that are created are made invisible
And to prevent lag
none of what you're saying makes sense
please provide more context
are you trying to achieve object pooling or something
The game I'm working on is zombie survival the problem I have is that I have a zombie spawner when I kill the zombie the game object that is the zombie destroyed it self so to fix that I made it go invisible but when new zombies appears it is invisible
Can I send videos?
when I kill the zombie the game object that is the zombie destroyed
yeah that should happen if you aren't pooling them. why is that an issue?
It looks like you've independently come up with the concept of object pooling. You've got the basic concept right, but might be a bit confused on the implementation. Here's a tutorial on the concept:
https://learn.unity.com/tutorial/introduction-to-object-pooling
how do i fix that
you don't
because it's not an issue
are you getting an error or something
are you instantiating separate gameobjects with a prefab?
ty
i see i got it ty
what would be the best way to check if a wave has no more enemies, then spawn the next available wave?
when enemy gets removed, remove it from a list you populated, then check the count left in that list
the "best" imo is using events for this
how can I make walking better I dont want this to happen
and these are my animations and script.
https://hatebin.com/rivpipcygk
my problem is player vertical camera jitter lag when falling. I fixed it by turning interpolate to none on my rigidbody but then it made my game feel horrible and the bullets are super laggy now. Is there anything else I can do to fix the jitter lag when falling without turning off interpolate ?
I can send my player movement or camera script
would just adding cinemachine to my camera potentially fix my problem or is there another step I should do with cinemachine
cinemachine is a gameobject
you can make it follow a gameobject you assign in the inspector
what if my game is first person, what would I make it follow?
https://pastecode.io/s/3ha6snzi
so here is my camera script.
first, I'm setting the direction in which the player is start facing, then I check if game is playing, if so then I can control the player looking around. Next is setting the sensitivity and camera rotation logic along with if im on a wallrun which is probably where my issue is somewhere
- on the y axis, if I move too fast sliding to rocket jumping. Its like the camera starts kicking back trying to get itself back in place
is camera child of your character
no. On my player there is a cameraPosition. There is another gameObject for cameraHolder with my main camera being a child of that.
In the photo, cameraHolder takes in camera position
do you set cameras position in MoveCamera script?
maybeusing fixedupdate can solve or making camera child of the player and not setting it by script
yes
Heres the moveCamera script. In this script I tried making it fixed update, but then the camera become super unsmooth
i think i found the problemmm
what is it
guys why does my new input manager package thing not look like the tutorials? I cant assign any global actions or anything
On my main camera, theres a script to handle player clipping. When I turned it off the bug went away but now I can look through wall if im next to one and look all the way down. fixed one issue to have another lol
use LateUpdate to move a camera so it happens after other stuff moves
thank you n I appreciate ur time.
Okay this is puzzling for me. I'm working on my first 2d sidescroller as a learning project, and I am just this simple script for the camera to follow the player:
public GameObject playerDefault;
// Update is called once per frame
void LateUpdate()
{
transform.position = playerDefault.transform.position;
}
}```
But when I actually playtest, the camera does position itself at the player, but it doesn't show anything except the empty background...
any idea what could cause that?
wont it cull the object uf its inside it?
Oh, so even though it's 2D, I need to offset ?
just in case
https://pastecode.io/s/wtjmpi48
heres the script that messed up my camera. When this script was active, the camera starts kicking back trying to get itself back in place if moving too fast. I turned it off and everything is fine now
youre not just looking at the thing, youre inside of it
you need to zoom out away from it
yes, unity has a 3d world, being 2d just means the camera is orthographic instead of perspective, it needs to still be a distance away from the player
Ahhhh yeah that makes sense now. Ty.
@naive pawn hey mate did you happen to catch my question?
please don't ping random people to look at your question, if you haven't got an answer just bump it
sure no worries
use a cinemachine2d. you can get it from package manager.
(you don't need to do that.)
guys why does my new input manager package thing not look like the tutorials? I cant assign any global actions or anything
tutorials might be outdated, try !learn maybe?
:teacher: Unity Learn โ
Over 750 hours of free live and on-demand learning content for all levels of experience!
Yeah so this is the older system I think
Unity keeps telling me to use the new one but its messed uppp
not much we can go on from here you have to show the exact error and issue comparison
you should use the new input system, yeah
whats that for anyway? i never had to do any of that and use Input system daily
no idea
I dont know what any of it is
I want to learn it but I cant find any resources at this pass
Ive been using the old system for ages but i figured its time to upgrade
I follwed the unity doc information on the setup but their pages look suuuper different to mine
Yeah thats the page im on
yeah I never did it that way idk lol just create a new input system action map on the PlayerInput component
can someone take a look
Hi so I followed a tutorial for making outline shaders, and after Iโm done it just looks super janky and has these black pixels everywhere, does anyone happen to have experience with sprite outline shaders that I can maybe look at? I imagine itโs pretty simple lol
Using shader graphs
this is a code channel
#archived-shaders
Cool didnโt see that one ๐ญ
can someone help me with git hub? Basically I made changes to my project which I didnt push to the github yet. I dont like the changes on my local disk and want to revert to what I had on github yesterday. im not sure how to do this
I'm following instructions for the last project in the Junior Programmer course and it says to "Select Canvas in Inspector. In the window for Player Name Input assign the Text component of the InputField" but when I try to drag it over, it doesn't let me put it in the box. Does anybody have a clue as to why?
if you can't assign the object, it doesn't have the correct type
make sure you're not mixing TextMeshPro components with Text components
The text component to be moved is TextMeshPro for sure, but I'm not sure about the destination. It looks like it might be expecting Text, but I'm not sure how to check, let alone fix it... ๐ฆ
did you create this Menu UI Handler component? please share the code if so
most likely you just need to change the type from Text to TextMeshProUGUI
!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.
you don't have to share the entire thing, just the line where you're declaring playerNameInput
[SerializeField] Text PlayerNameInput;
So just switch that to [SerializeField] TextMeshProUGUI PlayerNameInput; ?
What about the later reference to PlayerNameInput.text; ? Do I need to adjust for this change or can that stay the same?
lol fair enough
that's just how you'd do it in general lol
if it does error, you'd have to check docs for what the right property is
you should check regardless to make sure it's not subtly different, but i mean, this is pretty straightforward lol
That does seem to fix the problem. I would like to check the property though, as you said. I would just google TextMeshProUGUI, yeah?
yeah
cool thank you
some extra keywords like "unity" or "tmp" would help ensure you get the right docs
and you could also just go to tmp docs and search the class there
tmp docs are pretty bad
I am experiencing a weird issue when editing code in this snippet
int xCoord = Random.Range((int)currentRoomPosition.position.x-3, (int)currentRoomPosition.position.x+4); int yCoord = Random.Range((int)currentRoomPosition.position.y-2, (int)currentRoomPosition.position.y+2); float snappedX = xCoord * 0.64f + 0.32f; float snappedY = yCoord * 0.64f + 0.32f; Transform spawnPoint = new GameObject().transform; spawnPoint.position = new Vector3(snappedX, snappedY, 0.0f); //spawnPoint.position = new Vector3(xCoord, yCoord, 0);
editor (2022.3.20f1) stops responding and keeps on using more memory when attempting to launch the game, but if the commented line runs it works fine
any solutions?
!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.
new GameObject().transform
Probably related to the mem problem
How to stop two dynamic rigidbody2d gameobjects from pushing eachother/affecting each others veolicities on collision while still wanting to detect collision by code and without freezing position
Do you want them to collide at all? What's the use case here
well i want to specifically detect the collision of those two objects but i still want one of them to be able to collide with other things
both use rigidbody to move
Could use triggers?
I was thinking triggers for detecting, but the case of having two rigidbodies, and only one rebounding off the other I think requires changing the matrix
If you need to detect collisions between those two but not have them physically collide
for camera control on the mouse, the path used to be called Delta [Mouse]
does anyone know the new path for the input system?
is it maybe just "mouse"? i remember there being a "delta" control type instead
if not, try asking in #๐ฑ๏ธโinput-system
theres several pathways under mouse. ill ask in the that chat. thanks!
delta pointer is what i use
have you confirmed that you are not over writing the velocity anywhere like i suggested
Yeah
show how you move the object
no, the player which is the one being knocked back
moveInput = Input.GetAxis("Horizontal");
rb.linearVelocity = new Vector2(moveInput * moveSpeed, rb.linearVelocity.y);
if (moveInput != 0)
transform.localScale = new Vector3(Mathf.Sign(moveInput), 1, 1);
rb.linearVelocity = new Vector2(moveInput * moveSpeed, rb.linearVelocity.y);
what a surprise, you over write the velocity
is it not only when moving the key
unless there's some logic preventing this code from running when no key is pressed or for the duration of the knockback, then no
of course if you do have logic that prevents this from running when you do not press one of the Horizontal axis's keys, then you never stop either
don't mix assigning directly to velocity with AddForce unless you know what you are doing. use one or the other. otherwise you need to prevent input from the player (and this code you've just shown from running) for the duration of your knockback so you don't just immediately assign the velocity again
thanks i fixed it
like this
use mp4 not mkv to embed the video in discord
also make sure to show relevant !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.
hello, i am trying to make an IK arm, however there are angle limits to how much the arm can bend. can someone help me remove them? code: https://hatebin.com/kwfmpzfwzd
Hey guys, I was thinking maybe I should just [SerializeField] all component references or object references because it's faster than doing
void Awake()
{
rb = GetComponent<Rigidbody2D>()
}
or
void Awake()
{
boss = FindObjectOfType<BossMovement>().transform;
}
Would that be good practice?
a serialized field is definitely faster than using any of the Find methods
Thats what I'm thinking, but I'm wondering if serializing everything is a good idea because in every tutorial I watch they using serialize things like values but not components/objects
it is perfectly fine to do so and is preferable over using any of the Find methods because those are all incredibly slow
Okay, thanks for clearing that up
Hello
Hello, I hope you have an enjoyable day
How to rotate an object toward another 2D
atan2
how should i be connecting my player to the ui? ive tried using events to notify the ui when values change, and it mostly works, but im left with placeholder values until the values change for the first time because i cant guarantee that the ui is ready to listen when the player object starts itself
my only other idea is to give the ui a reference to the player and read the values every frame but that seems wasteful
Events are usually the idea, but just communicating to the UI every time your health decreases or something similar is pretty standard
What is that menat ot mean
A good concept to learn is Singletons, such that you can call this UI statically without having to pass the reference around
can't you just use the built in lookrotation function?
Continue to use events, but also directly read the value once at the start when the UI is ready
if it's a component reference on the same gameobject, that should probably be done through GetComponent to avoid mistakes in setting (forgetting to set or accidentally dragging a different object)
Vector3 direction = thisPosition - thatPosition;
transform.up / transform.forward = direction.normalized;```
There's many ways you can rotate in 2D in unity, even using quaternions
quaternions are evil
People give Unity a lot of crap for not having traditional 2D, but having the ability to use those methods makes up for it
but necessary
okay ๐
// Set rotation using Euler angles
transform.rotation = Quaternion.Euler(0, 0, angle);
// Smoothly rotate to target
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 10f);
// Rotate around target's position
transform.RotateAround(target.transform.position, Vector3.up, rotationSpeed * Time.deltaTime);
// Align object's up direction with a vector
transform.up = direction.normalized;
// Rotate to face the target
transform.LookAt(Target);
// Rotate around Y axis
transform.Rotate(0f, rotationSpeed * Time.deltaTime, 0f);
soo many ways to rotate stuff
i still dont know which one my favorite..
I tend to use rotation = Quaternion.AngleAxis the most i guess
will try, thanks
if i plug the player into a [SerializeField] on my UI, will that guarantee that the player awake and/or start is called before the UI start/awake? never really thought about how that works
I usually use the atan2 for rotating towards another object
Quaternions just donโt work for 2d ig
atan 2 is normally the next step after getting a direction
Yeh
lot of those methods require a bit of math before hand
then u got magic ones like LookAt()
which im pretty sure also uses Atan2
Vector3 direction = target.position - transform.position;
float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;
transform.rotation = Quaternion.Euler(0, 0, angle);```
my golden rotation code
transform.eulerAngles = new Vector3(0, 0, Mathf.Atan2(target.y - transform.y, target.x - transform.x) * Mathf.RadToDeg);
one liners eh
i was already on that one line and didn't feel like making more stuff lol
that makes me wonder if theres any optimizations to be had to write a little extension method to pass in two directions and just get the angle needed w/ the atan2 and the conversion
I use that too
No, referencing another object has no affect like this. If both objects exist in the scene, both will call awake before start is called at least. Look into the execution order listed on the docs for the exact details
Also if you need a specific order, you would need to implement that yourself, call the functions you want in a specific order
This is like the universally known rotation code for 2d
Itโs about the same through other game engines that donโt already have a function for it
lol.. facts.. its the one all the search engine AI's throw at you
just trying to think how id make sure the player stats are initialized before the ui tries to read them
i cant look at the code rn which definitely isnt helping but maybe i can just make sure the player stats are calculated in awake and then read them in the ui on start
thanks again!
public override void _Process(float delta)
{
Vector2 direction = target.Position - Position;
float angle = direction.Angle();
Rotation = angle;
}``` seems Gadot *does* have that extension method ๐
yoink
atan2 is such a godsend, ive used it for 2 robotics competitions lol
i think Dot product wins that title for me
Defo
i haven't had to use it. what did you use it for?
8Directional Sprites
Thatโs what I was gonna say ๐
ah, i thought you meant in robotics and i got quite confused lmao
yeah i see what you mean
ohhh.. nah for robotics im still writing Blink Hello World code for my ESP32
you got me beat
well yea the usual rule to follow will be
use awake to initialize and calculate my own values
use start to grab references/values from other scripts
though this doesnt really apply for example if you are spawning the player into the scene after start runs. So then this is when you'd need another script which initializes the player and notifies other objects that the player exists.
i don't think that application is applicable for games since most are in cartesian systems already, so joystick input can be used as-is instead of direction really mattering ๐ค
Awake <- Me
Start -> Them
for rare occasions I set manually execution orders for a gamemanager or such to fully initalize first
(i was using atan2 to process joystick input into a direction for movement)
You need to do that?
for some systems, yeah
I have not even gotten past the 3d printing stage ๐ฅฒ
was trying to make a robotic arm and I have all of the components for it
just have not 3D printed the "skeleton" yet
its ~~fun ~~ cheaper (lol) to do real-world projects like that In Unity first
if you have a 3D printer you can easily cut costs, the electronics are an exception of course
Itโs free (unless youโre using the pro unity version, idk who would)
does anyone have ideas for a project?
Learn something new
usually that follows with a project
I can't tell you what you're gonna like lol
Unity has some many systems
if you were to make a game that involved combat with weapons, would you include a script on the weapon itself that dealt with the functionality of doing damage? idk if that makes much sense, but what iโm trying to do is come up with a good way to structure my game so that i donโt regret it down the line
sure, that'd work
it's up to you ig
it's what I do as well
makes it easier to implement carrying the stats after dropping the weapon
brawl stars
make it multiplayer if you want a challenge
combat with weapons
This is really just too vague. The answer is, it depends.
So I made a GameManager script, and its icon turned into a little gear instead of the traditional c# paper that I'm familiar with. What's that all about?
in the assets menu or in file explorer?
ive always wondered that
it's just a bug that has been around in unity for a very long time. it's actually been fixed in unity 6
it's just a thing. It doesn't do anything more than that
just based on the name
i thought it was a unity easter egg or something
it sort of is
just *Manager.cs?
Ah ok, good to know I'm not overriding something special or something
GameManager.cs
no it's literally just GameManager.cs
wtf lmao
so in my game, i plan on implementing multiple melee weapons (and maybe ones that shoot projectiles). the player and enemies can both perform combat actions like swinging the weapon. right now, i handle combat with a script on the player/enemy game objects. the player executes the attack by pressing the left mouse button, and the enemy does if the player is in the โattack spaceโ (some area that triggers the enemy to chase the player).
when the player or enemy swings their sword, and the swordโs collider detects a collision, it raises an event that the targetโs health component listens for, and then promptly decreases the health.
this is fine for now, but thereโs an issue with this. since the enemy follows the player, thereโs a chance it will hit the playerโs sword even when the player is not swinging, which causes the enemy to lose health, and the enemy should only be damaged by the sword if the player is swinging.
iโm sorry if this is too long winded btw
Using collison callbacks for melee weapons is not generally a good idea
It's better to use direct physics queries
as in raycasting or spherecasting?
hmm im still struggling pretty hard with this
i have:
- a LevelManager script that spawns my Player inside of its Start() method
- a Player script that fires a HealthChanged event when it gets hurt
- a PlayerUI script that adds a callback to the HealthChanged event in its Start() method
i want the player ui to update with the players health as soon as the player spawns, but the player could spawn before the ui does and i cant find a way to handle that
depends on the trajectory
a spear or a rapier might use a raycast, a greatsword might use a boxcast
have your level manager spawn them both
if you need something in a specific order, make a higher level thing which enforces that order
yeah that figures. idk i wanted to leave some room for the player or the enemy to "miss" which is why i thought about those physics callback methods because to me it was the closest thing to realtime combat simulation
well "real time" in the sense of getting instant feedback when you attempt to attack
whatever solution you use, you probably want to define when the weapon is 'active' and only register hits while that is the ase
ase?
case
can anyone help me with this, i as following brackeys tutorial on how to make a game in unity using c# and im literally at the end of the game, ive done the credits, menu, all of it but im getting tihs error " error CS2006: Command-line syntax error: Missing '<text>' for '-define:' option " can anyone give me some troubleshooting because i dont feel like it would be good to post 6 scripts of code right here unless that could help you understand how to solve my problem
For starters, take a screenshot of the error and it's details.
And then also explain when it appears.
what do you mean by explain when it appears?
like when the error appeared while i was doing the game? if so it was after i finished putting all my scenes into the scene list and after completing the menu scene
If you clear the console, does it reappear? And when?
it just doesnt let me clear it
after pressing clear its like i didnt press it at all
according to chat gpt, (which im not sure if it as reliable so i came here) my scripts arent the problem
Yes, it's unlikely that your scripts are the problem.
Did you try restarting the editor/PC?
And when did that error start appearing?
Was it there from the very start perhaps?
im not exactly sure when the error started appearing cuz i did multiple changes before saving
im no trying to restart my editor
ok this is gonna sound really dumb but how do i get out of this page
Top right Layout->Default
is there any way 2 get coordinates of the most right pixel in 3d game?
i mean, i need some 3d object to be at the edge of the screen regardless screen parameter's of player
i have successfully recreated about 80% of the chrome dino game
- create a script
- create a public float in it
- change the value of the variable somewhere
- profit?
Sounds like a UI object, so maybe use ui to render or position it.
ty
no, 3d object
I mean, I get that it's a 3d object, but it's purpose is a part of the UI, is it not?
hello pls can someone guide me on how to make seperate animations for every move for a pokemon game pls I have the scriptable object as well as the animation clip but don't know how to implement it
something like this
If you're gonna use the animator, you'll need to create states for different moves and play them directly or via setting parameters in code. Basically, learn how to work with the animator.
Then as I said, use ui. Either use a raw image with a rendertexture and render the object to it, or place it in the canvas hierarchy directly and scale accordingly. The former is the recommended way. There might be issues with the latter approach.
no, this object needs to be 3d
Yes so I made the animation to an image
I get it. It will still be a 3d object.
how do i find a component but i dont know where it is
is there a way to find it? i forgot what object i put it in
nvm i foind it, its find references
Does anybody know why when I let the card down anywhere it stays there but if I put it on a wrong dropzone it goes back as inteded?
https://pastebin.com/axnqR8bB
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
if (currentDropZone != null && (currentDropZone.name == "Crescator1" || currentDropZone.name == "Crescator 2"))
Im so dumb ty
ok, i don't understand, wdym cause when i put it in the canvas i don't see it
if in ur variant it'll be overlay anything not in canvas, this variant isn't right in my situation
where do you see greyed out functions there
they maybe not gray, but they are more transparent
the start and update
theyre darker colored or something
I believe this is a known bug in VS 2022
i think it's cause it has 0 references
but i dont want it to be dark because of that
this may help
https://developercommunity.visualstudio.com/t/Private-Unity-messages-incorrectly-marke/10779025
ty
having no references on the Unity monobehaviour methods is normal, they are automatically called
hello pls can someone guide me on how to make seperate animations for every move for a pokemon game pls I have the scriptable object as well as the animation clip but don't know how to implement it
not really a trivial thing to do especially if you have no experience with SOs
