#💻┃code-beginner
1 messages · Page 319 of 1
I had logs on both
non came
Should I show you all the scripts used for the swap system?
At least the ones that you expect to be calling those methods
how can I create an object at the point where my mouse curser is?
Which of those should call the methods?
the invokes?
That's why I added them
You asked why the weapon swapping isn't working
Which part is supposed to call the methods that do the weapon swapping?
hii, im doing a school proyect and i need to print the score in the GameOver scene, but they are in two different scenes, and i dont know how to do it
I think I od have some asmdef issues after importing steamworks into my project, other namespaces are no longer recognized, althought i dont have any errors in the console and can enter playmode just fine.
how can i resolve this?
they were supposed to be called on animation events
I actually fixed it now
they are now being called but I'm getting new errors
I suggest you look at the documentation for DontDestroyOnLoad
ok, thanks
im typing my code in visual studio and now i cant write in between two letters it just deletes whats Infront of it probably hit a hotkey or something, can someone tell what to press?
you have switched from insert mode to overwrite mode. Hit the Insert key on your keyboard
thx
Hey, I have these lines of code, but I'm getting an error that the function "ClosestToEnd" doesn't exist because it's referencing the GameObject - how do I reference the "tower" itself ``` public GameObject turret, building;
public void CloseEnd()
{
turret.ClosestToEnd();
}```
is 'tower' a script of yours?
Use your actual script class instead of GameObject of course
Why write GameObject if GameObject is not what you want
It's "turret" but yeah.
what? that makes no sense
Long story, I build the turret on a node, so the node uses the gameobject to actually build the turret
That is meaningless to me
Is there a script named Turret or not?
Yes
Then use that
If I do that then I have to make everything static which I can't do because I need to manually set the option in the inspector
You don't have to make anything static
Nobody said to make anything static
Where are you getting that idea from?
I'm making a rhythm game and am storing the notes that need to be spawned and clicked on in a list, I am concerned about the list being too large and it being too intensive to loop through each frame to check what notes need to be spawned next.
is there a smarter way to go about this?
You said "then use that" which suggested to me "Turret.ClosetToEnd"
No you're not listening
public Turret myTurret;
I said stop using GameObject as the type of your field. Use your actual script class like this ^
Then you can write myTurret.ClosestToEnd(); or whatever your function is called
You don't need to loop through the entire list every frame
Keep an index of the current note
Increment it as you move through the song
this is for something like ddr or osu mania where multiple notes can appear at the same time
I guess but wouldn't I lose precision by just using the index?
You only need to peek left/right in the list long enough to cover the maximum allowable input error time
ah
That's a max of like 5 notes to look at per frame
I guess that makes sense yea 
then I'll just implement an int to check x amount of list items ahead
thanks
Thank you very much for this. Is there anything inherently wrong with doing this instead? turret.GetComponent<Turret>().ClosestToEnd();
It's kinda pointless, you are running the getcomponent for nothing
If you don't need to interact with the GO directly, there is no reason to store the reference to it rather than just the script
Yes, it doesn't make much sense.
I appreciate that you don't know how the code is put together, I'm just wondering if there's a noticeable different computationally. In my case, the game is essentially paused so I'm not too concerned about that and I got an error with 'myTurret.ClosestToEnd'
There are 2 visible possible mistakes, according to the error you're having
https://gdl.space/efabiyonoq.cpp Guys, I'm trying do make an image's sprite change by calling the corresponding the ChangeItem buttons with on click events, but only the code from the start function works for some reason
Can anyone help me investigate this issue and help me resolve it?
-
myTurretdoesn't have the type you expect it to have, as you have sent in the previous response, that's whyClosestToEnddoesn't exist
-
ClosestToEndis supposed to be a method, as you have also shown in your previous response, and requires the parentheses after it:ClosestToEnd()
i want to add characters in unity and when in first person you can see your hands/body. and id its multiplayer i want others to see my character aswell. can someone tell me how or send me a video on how to do this
thisTurret.ClosestToEnd(); = Object reference not set to an instance of object
Alright, then thisTurret is null, which means it is not assigned
Throw some debug logs in your methods to make sure they are being called at all
Premise - it's a tower defence game, I have ~50 nodes and ~6 towers. I'm adapting the node options so that I can change a setting on my turret, of which, the node didn't need to know about the object specifically
Alright, are we going to read the actual question too?
I appreciate the help I have received, I'm trying to simplify my question without having to explain everything - I'm an amateur trying to learn.
I just realized I turned the Interactable checkbox off lol
hey guys! does collision work different in the case of prefabs? I have a simple "player" object (handles movement, has rigidbody2d) and "food" object. Both objects have BoxCollider2D. The collision is working fine (Debug.Log("Triggered with object: " + other.gameObject.name);)
but when I create instances of food scattered across the area, the collision simply ceases to work and nothing happens. Do I have to somehow alter the collision to handle all instances of my object? How do I achieve that?
prefab shouldnt break colliders, no
object hit object boom
it's probably that when you are creating the instances, their colliders are inside the collider of the floor, increase the altitude of the instances a little i guess
prefabs are just like any other gameobject without the ability to reference scene elements
floor? you mean like a literal floor? it's a top-down view ;D
do both colliding objects have a collider and a rigidbody, plus neither of them should have istrigger on
make sure it's rigidbody2d rather than simply rigidbody
same for collider
white - player
green - food
grey blobs - simply background texture)
all i want is for the white to collide and destroy the green thingies
and as I said, in the case of 2 simple game objects it works fine
but when I generate multiple instances of green, the collision ceases to work
!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.
w8 i have no clue how to post code sec
using UnityEngine;
public class SquareGenerator : MonoBehaviour
{
public GameObject squarePrefab; // The green square prefab
public int numberOfSquares = 50; // Number of squares to generate
public Vector2 areaSize = new Vector2(50, 50); // Area size for square spawning
void Start()
{
GenerateSquares();
}
void GenerateSquares()
{
for (int i = 0; i < numberOfSquares; i++)
{
// Generate a random position within the specified area
Vector3 spawnPosition = new Vector3(
Random.Range(-areaSize.x / 2, areaSize.x / 2),
Random.Range(-areaSize.y / 2, areaSize.y / 2),
0); // Ensure z-position is zero for 2D
// Instantiate the square at the generated position with no rotation and as a child of this GameObject
Instantiate(squarePrefab, spawnPosition, Quaternion.identity, transform);
}
}
}
This generates the green thingies
what happens if you just duplicate that one object on the scene
might be procedural
using UnityEngine;
public class FoodComponent : MonoBehaviour
{
// This is just a marker component; no need to add anything here.
}
This is what chatGPT told me to do to reference the green thingies
using UnityEngine;
public class CollisionDetection : MonoBehaviour
{
private void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("Triggered with object: " + other.gameObject.name);
}
}
and this is supposed to handle the collision
is isTrigger on(for the white circles)?
yeah, for both
😮
then it wont work
make sure the prefab is updated
not weird at all
it would cause strange problems if triggers detected other triggers lol
does it matter? I thought the only requirement is that at least 1 has a trigger collider and 1 has a rigidbody
sad news
still doesn't work
can you send a screenshot of the collider and rigidbody for both the objects in question
and, it seems i don't really know how to white circles came to be, but make sure their z position is just like green food(0)
yeah their z position is set to 0 in code
this would help
food does not have a rigidbody?
the white player pixel is just an object with sprite renderer and movement is handled by
using UnityEngine;
public class Draggable : MonoBehaviour
{
public float smoothTime = 0.3f; // Smoothing time, lower is faster
private Vector3 velocity = Vector3.zero; // Reference velocity for the smooth damping
private void Update()
{
Vector3 targetPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
targetPosition.z = 0; // Ensure the sprite stays on the 2D plane
// Gradually move the position towards the target position with smoothing
transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, smoothTime);
}
}
oh, hold on
remember that you are calling ontriggerenter
if the food is generated inside the white circles, it will not be called
they need to enter from outside
hence ontriggerenter
is that the case?
how do i reference a game object that was created in one void in a different void?
woo sounds cool but what's a void
they meant function type void i believe
yeah
you can cache that created object as a global variable, or pass the created object as a parameter
global scope variable, or a return type. google and see which fits best
in the 2nd function
as well as parameter yeah depends how it's called
Hello everyone, i want a tool tip to appear over the inventory slot when i hover over it with mouse cursor. Tooltip appears but it constantly turns on and off as long as the cursor is on the slot. I think the issue lies with the update method where it changes the transform position of the tooltip. Here's the code
private void Update()
{
if (tooltipBackground.activeSelf)
{
tooltipBackground.transform.position = Input.mousePosition + new Vector3(10, -10, 0);
}
}
void SpawnObject()
{
var spawnedObj = Instantiate(...);
DoSthWithobject(spawnedObj)
}
void DoSthWithobject(YourObjectType obj)
{
}
@scenic saffron
ok thx
it just keeps shifting by new vector3(10, -10, 0) every time update is called
can someone explain why my dash counter dosent let my dash() work
if (dashes < maxDashCount)
{
timer += Time.deltaTime;
if (timer > cooldownTime)
{
dashes += 1;
timer -= cooldownTime;
}
if (Input.GetKeyDown(DashKey) && dashes > 0)
{
dashes -= 1;
UpdateUI();
Debug.Log(dashes);
Dash();
}
//UWU
}
void UpdateUI()
{
for (int i = 0; i < maxDashCount; i++)
{
DashChance[i].SetActive(dashes >= i);
}
}
type in `
!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.
ok but why turning it off when it does it?
col isnt being printed idkl why pls help
if it gets shifted, then mouse is no longer over it. hence get's disabled
how can i fix it?
can you send me an image of the inventory slot
incorrect spelling
where
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
I'm getting this error when trying to get my character's run cycle to work, it says that AnimState does not match but that's the float state I set up in the animator, im lost
i am using it i set it up it works just that didnt
well, in this case it won't
it considers the function with double s a new function you made
yeah double s again
so without the double s
Spell the word correctly 😉
alr thank you
you should basically not be calling that in update directly like that i guess, use OnMouseOver() function
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnMouseOver.html
the onmouseover function should be on your item slots. so when mouse is over them, you can enable the tooltip, and otherwise keep it disabled using OnMouseExit()
i use OnMousePointerEnter-Exit function
ok, i'll try this one too
thx
is it required in your case, because onMouseExit and OnMouseEnter seems simpler
sorry to bump again i just cant find a fix for this
can you post the error in ss
what error
Question, does anyone can explain the concept on how to make the player move with one of the 4 platforms? The whole Object is just 1 Element with 4 colliders that can be triggered and i simply rotate it from the origin, but sadly it's not as easy to move the player with it as having just a moving plattform going from spot A to B. (Or i'm just dumb)
Can i work something out, do i've to implement that into my PlayerMovement class or into my Rotationclass that triggers when player enters the trigger or do i have to change the whole object that rotates and structure it differently?
this is the only error i get
its not stopping from compiling and running, its just not playing the animation as intended
maybe it's an int?
wdym ?
Yeah it's ugly and harder to work with
Why subject yourself to that?
integer
how would it be an integer
click the dropdown to create a trigger. maybe you clicked the int option instead of float.
would i be able to check if animstate is an int ?
since it connects to these 4
im like 99% sure its a float
I did what u told me to do but now i cant reference the second function anymore
show
try setting it to smth like 1.1
okay yeah it doesnt let me
i guess gotta change it then
do you have ide configured
Possible ideas:
- The parameter name might have whitespace, could be named for example
AnimState - Parameter might not be float
- Your code might be attempting to change the parameter of a different animator than you think.
Let's start by showing your parameters panel and retyping that parameter name to make sure it's not 1 or 2
you cannot call MoveBlackHole(); that function needs a paraemeter
whats an ide
Ah, I spent too long typing, looks like the problem was solved
do you need decimal point precision
no just negative numbers to determine whether facing right or left
you could use mathf.round to just round it up
Thing you code in
ok
i mean
Either cast it to int (drop the decimals) or use Mathf.RoundToInt to get to the nearest integer
Mathf.RoundToInt()
!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.
i just gave short form
That's not the same error!
okay let me try that
okay well the error is gone but the animation still isnt playing
bruh that's some other problem
i gtg
alright
what parameter do i have to use
You wrote it. Pass in the parameter you expected it to have when you wrote it.
Ok, current issues with my enemy AI script: the AI is stuck on the hunt mode, AI movement does not abide by the speed and other movement values in the Nav Mesh Agent component. Script: https://hastebin.com/share/didaheqali.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
void update()```
You didn't spell Update correctly
Im getting this error with my animations now, i have set up the conditions for anim state to change when its equal to 40 which it does, but it only repeats the first frame of the animation
tried it, didn't work for some reason. I attached a collider to the slots too. Still didn't work
If you're using UI you can't use OnMouseEnter. You have to use IPointerEnterHandler/IPointerExitHandler
you definitely don't put colliders on UI elements.
ohhhhhhhhh, my dumbass misspelled gameObject
any idea how i can fix the issue i posted above?
Make sure your tooltip UI has raycast target disabled
That seems like it's repeatedly entering this state. Do you have a transition from Any State to this state? That would include this state itself so it'd just keep playing as long as the condition is met
Which animation is the one that's stuck
What are the conditions from idle to run and run to idle
yeah its because the run to idle was set to not equals 2
i had to update it to 40
do you know how id go about getting the animation to play for when im running left ?
currently its only when the condition is 40 which would be for moving right, but AnimState can enter -40 to indicate moving left
i did it, still happening
you'd have to show how everything is set up
You showed an Update function which doesn't seem all that relevant
how are you showing/hiding the tooltip
and show the inspector(s) of the objects involved, including the tooltip UI
public void OnPointerClick(PointerEventData pointerEventData)
{
UseItem();
}
public void OnPointerEnter(PointerEventData pointerEventData)
{
if (!empty)
{
tooltipBackground.SetActive(true);
infoText.text = type + "\n" + description;
}
}
public void OnPointerExit(PointerEventData pointerEventData)
{
tooltipBackground.SetActive(false);
}
This is the code which shows and hides the tool tip
Right so this absolutely sounds like the tooltip is blocking the raycast
So can you show the inspector of your tooltip?
BTW the issue is that it rapidly turns the tooltip on and off, yes?
ok and does this have any child objects?
yes, textmeshpro
Ok turn raycast target off on that as well
You could and should also just add a canvas group to the root object of the tooltip:
https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/class-CanvasGroup.html
And disable it from there in one spot
it doesn't have a raycast box
Okay it worked. Thx a lot for the help!
So it's raycast issue huh? First time running into it
When raycast target box is checked, mouse cursor recognizes it as an interactable object, something like that i guess
Yes which leads to...
When you showed the tooltip, the event system was detecting the tooltip as the thing your mouse was over. This meant your inventory slot was no longer being detected and so it was calling OnPointerExit. That turned off the tooltip which means that the slot was once again detected, and it called OnPointerEnter. And it goes back and forth like this forever.
thx for the help and the info again
I think I'm confusing myself with how quaternions and eulers work here, I just want the camera to rotate 90 degrees each way when the button is pressed, but at a certain point it just chooses to do a full 270 degree turn. Why is that? ```cs
public float rotationDuration;
public AnimationCurve rotateCurve;
public void RotateRight()
{
StartCoroutine(SmoothRotate(90, 0));
}
public void Rotateleft()
{
StartCoroutine(SmoothRotate(-90, 0));
}
private IEnumerator SmoothRotate(float yangleToRotateBy, float xangleToRotateBy)
{
Quaternion initialRot = transform.rotation;
Quaternion targetRot = Quaternion.Euler(initialRot.eulerAngles + new Vector3(xangleToRotateBy, yangleToRotateBy, 0));
float timer = 0f;
while (timer < rotationDuration)
{
timer += Time.deltaTime;
float t = Mathf.Clamp01(timer / rotationDuration);
transform.rotation = Quaternion.Euler(Vector3.Lerp(initialRot.eulerAngles, targetRot.eulerAngles, rotateCurve.Evaluate(t)));
yield return null;
}
transform.rotation = targetRot;
}
Why complicate this with .eulerAngles?
Quaternion targetRot = initialRot * Quaternion.Euler(xangleToRotateBy, yangleToRotateBy, 0));```
was just the only way I understood how they work
And again here:
transform.rotation = Quaternion.Euler(Vector3.Lerp(initialRot.eulerAngles, targetRot.eulerAngles, rotateCurve.Evaluate(t)))```
You are overcomplicating this with .eulerAngles and making it not work well
Just do:
transform.rotation = Quaternion.Slerp(initialRot, targetRot, rotateCurve.Evaluate(t)));```
You can "add" quaternions with the * operator. A * B applies A then applies B. So now the result is the combined rotation.
Slerp is spherical interpolation
it's used for rotating directions
Lerp is for linear motion
A good visual explanation:
ah okay, that's good to keep in mind
and yeah, the rotation is working now. I didn't really know about the multiplication aspect
your problem was trying to do Lerp with euler angles
that doesn't account for things like 270 -> 0
It's one of the many reasons euler angles are often a bad way to deal with things
although it's got an issue which I've tried to resolve in other projects, but haven't figured it out yet. If I press the button while it's making a rotation, it jumps there and starts the next one. What could I do considering it's a coroutine at the moment to have it start the next rotation from where it as and not make that jump?
depends what you want
do you want to disable the ability to rrotate until it's done?
Or do you want it to continue smoothly rotating to the next one from its current position
To the next one if possible
You should cancel/stop the current coroutine and start the new one
didn't know you could cancel them
do you have to know one is running before you do?
Yep you can stop them!
https://docs.unity3d.com/ScriptReference/MonoBehaviour.StopCoroutine.html
if one isn't running when stop is called, would that throw up an error?
I think it's safe to pass null into StopCoroutine
you have to pass the coroutine into the function
You can do StopAllCoroutines to stop all ones on a gameobject too
hey can I get some help with my chess logic?
saying that the coroutine is null when I call stop, trouble is I've got some parameters to pass in
doens't make any difference
only my white pieces are able to capture,
and the pieces don't necessarily move when I tell them to
Did you look at the docs for StopCoroutine to see how to use it properly?
there is sample code
example:
// start:
Coroutine c = StartCoroutine(MyCoroutine(params));
// stop:
StopCoroutine(c);```
Yeah I looked at the example, since they are only ever going to pass in 3 seconds they can define it and stop it in update, but since the parameters will contain the angle to rotate at, wouldn't I need a separate IEnumator for each possible kind of rotation?```cs
public void RotateRight()
{
rotateCoroutine = SmoothRotate(90, 0);
StopCoroutine(rotateCoroutine);
StartCoroutine(rotateCoroutine);
}
public void Rotateleft()
{
rotateCoroutine = SmoothRotate(-90, 0);
StopCoroutine(rotateCoroutine);
StartCoroutine(rotateCoroutine);
}
this isn't right
you need to stop the previous coroutine
not the new one
I would recommend using a Coroutine variable instead of an IEnumerator
then you can do:
public void RotateRight()
{
StopCoroutine(rotateCoroutine);
rotateCoroutine = StartCoroutine(SmoothRotate(90, 0));
}```
if you want to use IEnumerator you have to do:
public void RotateRight()
{
StopCoroutine(rotateCoroutine); // stop the OLD one
rotateCoroutine = SmoothRotate(90, 0);
StartCoroutine(rotateCoroutine);
}```
Does anyone know what I can do to prevent this? I added a few model packs to an empty unity project and tried to commit to Github, with LFS enabled and currently LFS has 0 out of 2gb used on my account, with the latest .gitignore file as well.
had that before, but It ended up throwing up errors
show what you had and what errors you got
Had this before, stopping the previous coroutine, then making the next one.
public void RotateRight()
{
StopCoroutine(rotateCoroutine);
rotateCoroutine = SmoothRotate(90, 0);
StartCoroutine(rotateCoroutine);
}
public void Rotateleft()
{
StopCoroutine(rotateCoroutine);
rotateCoroutine = SmoothRotate(-90, 0);
StartCoroutine(rotateCoroutine);
}
And then ```NullReferenceException: routine is null
UnityEngine.MonoBehaviour.StopCoroutine (System.Collections.IEnumerator routine) (at <30adf90198bc4c4b83910c6fb1877998>:0)
RotateCamera.RotateRight () (at Assets/RotateCamera.cs:17)
Just do cs if (rotateCoroutine != null) StopCoroutine(rotateCoroutine);
Lookin good! Although now it can end up out of those 90 degree points I want it to rotate to, i can see why, but I'll have to fix that next
Ah yeah that makes sense. You should then maintain a separate Quaternion variable to hold the current target rotation
and use that as the basis for generating the next rotation
rather than transform.rotation
Sort of got there, it jumps to that next point again but I can fix that
my piece moving logic isn't stopping on my own pieces
white pawns are the only pieces that I coulg get to capture
ay it works! Thanks Praetor
and other pieces don't move
where is the camera
and what does the camera preview show
on top of capsule
actually when I zoom to see my capsule the terrain becomes invisible
send same screenshots but select camera in the hierarchy
Your camera is not positioned to see the ground
see this
Press F or double click it in the hierarchy to zoom in
Just looks like your camera is underneath the ground to me
Yeah because that object is underneath the ground
did you read the error
Trying to make a Player movement, but I'm getting stuck on the mouse rotation.
This is my CameraMovement.cs script:
void Update()
{
mouseX = sensitivity * Input.GetAxisRaw("Mouse X");
orientation.transform.eulerAngles += new Vector3(0f, mouseX, 0f);
transform.eulerAngles = orientation.eulerAngles;
transform.position = orientation.position;
Debug.Log($"{orientation.eulerAngles.y} | {mouseX}");
}
and this is my PlayerMovement.cs script:
void Update()
{
MyInput();
}
void FixedUpdate()
{
Movement();
}
void MyInput()
{
vertical = Input.GetAxisRaw("Vertical");
horizontal = Input.GetAxisRaw("Horizontal");
moveDir = transform.forward * vertical + transform.right * horizontal;
}
void Movement()
{
rb.AddForce(moveDir.normalized * moveSpeed);
transform.eulerAngles = orientation.eulerAngles;
}
However, when I look around it continue rotate, even though I don't move the mouse. How do I fix this?
orientation.transform.eulerAngles += new Vector3(0f, mouseX, 0f);
transform.eulerAngles = orientation.eulerAngles;
shouldn't that assignment be
transform.eulerAngles = orientation.transform.eulerAngles;
? And do you need the orientation transform if you are putting that same rotation on your gameobject directly anyways?
Seems you are possibly mixing up Rigidbody and Transform movement/rotation
I'm having a few issues: only my pawns can move forward reliably, the knights, horses, king, bishop and rook are finnicky (they do work on occasion and not on others and I can't make heads or tails of what to debug)
I've stopped getting nullreference errors for my game manager implementation
My dark pawns like to overlap the white pawns instead of capture, even though my whit pawns capture normally.
The white long range pieces are ignoring the pieces around them in the checks for valid moves and I don't know how to fix that
- BitBoard
- BoardCoord
- GameManager
- ChessPiece
- Piece Setup
Need some help. I'm trying to lock constraints (2d) in my c# code but it's unlocking my z-rotation constraints when I don't want it to
!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.
literally told you how to paste code right there
and if it doesnt let you use a website, then make a better picture at least
RigidbodyConstraints2D are flags, and you're overriding them with RigidbodyConstraints2D.FreezePosition
If you want to add new constraints to your original ones then do rb2D.constraints = rb2D.constraints | RigidbodyConstraints2D.FreezePosition
If you want to remove constraints from your original ones then do rb2D.constraints = rb2D.constraints & ~RigidbodyConstraints2D.FreezePosition
Can be shortened to:
- Adding:
rb2D.constraints |= RigidbodyConstraints2D.FreezePosition - Removing:
rb2D.constraints &= ~RigidbodyConstraints2D.FreezePosition
Try this and see if it helps
so i wanna instantiate a ui element, but somehoiw the scale is always 8.some times the scale i want; e.g. prefab scale is 1 obj scale is 8: Transform obj = Instantiate(playerUIElement, childStartPosition.position, Quaternion.identity).transform; in the picture i set the localScale to 10
I've been trying to work on a smooth camera rotation some more, when you press a button it rotates 90 degrees correctly, but trying to add pitch has been a pain. I had a way to track the old yaw rotation, but now that I've introduced pitch it's complicated things. Is this approach at all right?
private IEnumerator SmoothRotate(float yangleToRotateBy, BuildCameraPosState cameraState)
{
Quaternion lastTarget = targetRotation;
Quaternion lastPitchTarget = pitchTargetRotation;
Quaternion lastPitchRot = curentPitchRotation;
Quaternion lastYawTarget = yawTargetRotation;
Quaternion lastYawRot = curentYawRotation;
Quaternion pitchTarget;
Quaternion yawTarget;
Quaternion lastCombinedRot = lastYawRot * lastPitchRot;
Quaternion lastCombinedTargetRot = lastYawTarget * lastPitchTarget;
switch (cameraState)
{
case BuildCameraPosState.SideView:
pitchTarget = Quaternion.Euler(0, 0, 0);
break;
case BuildCameraPosState.TopView:
pitchTarget = Quaternion.Euler(30, 0, 0);
break;
case BuildCameraPosState.LowView:
pitchTarget = Quaternion.Euler(-20, 0, 0);
break;
default:
pitchTarget = Quaternion.Euler(0, 0, 0);
break;
}
pitchTargetRotation = pitchTarget;
yawTarget = lastYawTarget * Quaternion.Euler(0, yangleToRotateBy, 0);
yawTargetRotation = yawTarget;
Quaternion combinedTarget = yawTarget * pitchTarget;
targetRotation = combinedTarget;
float timer = 0f;
while (timer < rotationDuration)
{
timer += Time.deltaTime;
float t = Mathf.Clamp01(timer / rotationDuration);
transform.rotation = Quaternion.Slerp(lastYawRot * lastPitchRot, yawTarget * pitchTarget, rotateCurve.Evaluate(t));
curentYawRotation = transform.rotation
yield return null;
}
transform.rotation = yawTarget;
}
``` it's all becoming rather hard to follow
!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'll want to instantiate a UI object directly as a child of the thing you want it to be a child of. If you spawn it as a root object then move it into the canvas it's going to have an incorrect scale
how can i do that?
Pass in the transform of the object you want it to be a child of.
https://docs.unity3d.com/ScriptReference/Object.Instantiate.html
Hey yall, what is the external link for posting large amounts of code for people to see? i forgot
You may also use the !code method
📃 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.
Oh, it wasn't supposed to be sent. I thought it doesn't work with inline code blocks.
do you have a collider on both?
make sure both objects are set up correctly to trigger the collision . . .
Yes
Both have to be trigger?
nope, the trigger object should have the script on it . . .
and at least one GameObject must have a rigidbody . . .
you can simply place a log in the trigger method instead of calling another method with a log . . .
I dont think thats right, doesn’t work anyway
don't think what is?
Still doesn’t work
The object with the script has to have the ontrigger
show how both objects are setup . . .
The Three Commandments of OnTriggerEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt tick
isTriggeron at least one of them - Thou Shalt have a 3D Rigidbody on at least one of them
My computers wifi modum is burnt
I cant use it to send screenshots
you're using a 3d physics method for 2d collisions . . .
Ohh, shit was that simple
I over complicated it lol
i swear, i was looking for this . . .
you need to look at the method name carefully. you misspelled it . . .
Yup
stop rushing and take your time. every line and word is important . . .
hello i have got a wierd behaviour when i run my game on the editor the game run normaly but whene i build it it give me error at runtime why ? error : CollisionMeshData couldn't be created because the mesh has been marked as non-accessible. Mesh asset path "" Mesh name "Cube"
Am reaching a dead line
On a rush
What did I misspell
Slow is smooth
Smooth is fast
and making these small errors will only impede you from completing, such as the 3d/2d debacle and this current, simple spelling error . . .
Capitalization issue
Did you go through every page?
hello i have got a wierd behaviour when i run my game on the editor the game run normaly but whene i build it it give me error at runtime why ? error : CollisionMeshData couldn't be created because the mesh has been marked as non-accessible. Mesh asset path "" Mesh name "Cube"
I need help. so I'm making a mobile game and I have added a joystick with some coding I found on YouTube. this error keeps popping up and I don't know how to fix it can someone help me. im a beginner btw
I've got a bit of an issue with the camera rotation script again, i've made a separate object that will have methods to rotate it up and down, with it's parent handling yaw. The yaw has a method that will rotate it around to move to 4 different spots around the centre, which works. ```cs
private IEnumerator SmoothYawRotate(float yangleToRotateBy)
{
Quaternion lastTarget = yawTargetRotation;
Quaternion lastRot = curentYawRotation;
Quaternion targetRot = lastTarget * Quaternion.Euler(0, yangleToRotateBy, 0);
yawTargetRotation = targetRot;
float timer = 0f;
while (timer < rotationDuration)
{
timer += Time.deltaTime;
float t = Mathf.Clamp01(timer / rotationDuration);
transform.rotation = Quaternion.Slerp(lastRot, targetRot, rotateCurve.Evaluate(t));
curentYawRotation = transform.rotation;
yield return null;
}
transform.rotation = targetRot;
}
But the pitch one is acting up a bit. if I rotate one to the right, the yaw game object has it's rotation changed properly. but I press right then down soon enough after each other, it teleports and the pitch gains the yaw of the parent, which isn't intentional as I want them both separated.cs
private IEnumerator SmoothPitchRotate(BuildCameraPosState cameraState)
{
Quaternion lastTarget = pitchTargetRotation;
Quaternion lastRot = curentPitchRotation;
Quaternion pitchTargetRot;
switch (cameraState)
{
case BuildCameraPosState.SideView:
pitchTargetRot = Quaternion.Euler(0, 0, 0);
break;
case BuildCameraPosState.TopView:
pitchTargetRot = Quaternion.Euler(30, 0, 0);
break;
case BuildCameraPosState.LowView:
pitchTargetRot = Quaternion.Euler(-20, 0, 0);
break;
default:
pitchTargetRot = Quaternion.Euler(0, 0, 0);
break;
}
Quaternion targetRot = pitchTargetRot;
pitchTargetRotation = targetRot;
float timer = 0f;
while (timer < rotationDuration)
{
timer += Time.deltaTime;
float t = Mathf.Clamp01(timer / rotationDuration);
transform.rotation = Quaternion.Slerp(lastRot, targetRot, rotateCurve.Evaluate(t));
curentPitchRotation = transform.rotation;
yield return null;
}
transform.rotation = targetRot;
Not entierly sure why it suddenly takes on that value when I never reference the parent at all
I need help. so I'm making a mobile game and I have added a joystick with some coding I found on YouTube. this error keeps popping up and I don't know how to fix it can someone help me. im a beginner btw
your format — or syntax — is incorrect. you have fields declared outside of the class . . .
so how do I fix this
make sure you understand what is a class and how to declare variables in c# . . .
!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
Configure your IDE so you get auto-complete and intellisense to avoid making syntax errors
place the fields (variables) inside of the class scope . . .
im laughing so hard cause im a beginner and what you just said went through my brain lol
idk what a class scope is
if you're a beginner, it's important to learn/follow a beginner c# tutorial to learn the basics. you can't start without any prior knowledge . . .
A { } is a scope, to keep it simple
it's hard to help if you don't understand the help given . . .
😦 time to learn
The simplest possible class declaration is...
class MyClass { }
In this case, the class body -- { } -- is completely empty.
you generally want to actually put things into your class
class MyClass {
public int myIntField;
public void SomeMethod(int florp) {
Debug.Log(florp);
}
}
This declares two members inside of the class: a field and a method
would this be correct?
Is that gpt 
run it and see if you get any errors . . .
yes lol
we are not interested in helping you with machine-generated spam
See #854851968446365696 and #📖┃code-of-conduct
That is against the rules
okay some im having a brain fart atm , rn im working on the save and load system but since i have a CharacterStats script and a PlayerStats which im just overriding some stuff from CharacterStats but i have the health and maxHealth variables only in CharacterStats script and i wanna only save the players health cause im only overriding a void from CharacterStats script and PlayerStats is a subclass of CharacterStats , how could i go on about and only save the players health and not have to get it from the CharacterStats script and well save only the players health n stuff
unsurprisingly, the GPU did not understand that a member cannot have the same name as the enclosing type
sorry didn't know
look at ur joystick variable name and at your class name
they are idk maybe the same possibly
that is a problem, yes, but the member declarations have been jammed between most of the class declaration and the class body
that is a larger issue
oh goddamn didnt saw 😭
and also shouldnt the CharacterController be like that greenish color
the IDE was not configured, yes
Visual Studio will display "Miscellaneous Files" up there if it doesn't understand which assembly the file belongs to
thats a problem lol
visual studio code is less obvious, although it will generally show "Projects: 0" (or nothing at all)
(that's a lot of assemblies...)
good lord
115
kinda obv you cant have a variable the same name as ur class name lol
also could i maybe have some help here brkasknbka
how are you actually serializing the class?
JsonUtility?
that should serialize the fields from the parent class just fine
maybe i don't understand your problem
oh, CharacterStats is a MonoBehaviour
i'll need to see the actual serialization code
from the SaveAndLoad script?
yes
dont have anything atm
i just wanna save the players health and max health but those varibales are in CharacterStats script
PlayerStats is a subclass of CharacterStats
https://gdl.space/avusogoyan.cs
i dont know why this isnt working. i want the xp that is too much after the level up to be added to the next level
i think the actuall problem is with the velocity but i dont know why
its the 6th parameter from below
okay fixed it i think , the health and maxHealth variables were protected in the CharacterStats script so i made them public and now i can easily do playerStats.health 
What does this mean?
It means you tried to use a reference that wasnt pointing at anything
on line 20 of joystick.cs
As you didnt share the complete code, the only thing that looks strange is this
Fortschritt.value = currentXp;
lower case c rather than upper case
you have to assign the reference in the inspector
i actually did share the whole script
you did not - as the class declaration and using directives are not included
okay wait
no you did not, no variable currentXP in the script shared, also not complete
Something on that line is null but you're trying to use it anyway
You shouldn't add "cs``" to it for no reason
that's only for formatting within discord itself
okay
(it's also not correct. The correct thing is:)
```cs
// code here
```
print("Like this");```
Your code is overcomplicated
so it's hard to tell exactly
I would recommend learning to use arrays and structs, which will make this code a lot simpler
also coroutines
the problem is in this section i ques: (xpvisual = CurrentXP; float currentXp = Mathf.SmoothDamp(Fortschritt.value, xpvisual, ref velocity, speed * Time.deltaTime); Fortschritt.maxValue = MaxXP; Fortschritt.value = currentXp; text.text = CurrentXP + "/" + MaxXP; if (Mathf.Abs(currentXp - xpvisual) < 0.001f) { CheckLevelUP(); })
but the velocity goes crazy when the XPVisual is greater than MaxXP
any way to simplify this? i just need to update the y coordinate transform.position = new Vector3(transform.position.x, a.y, transform.position.z);
var pos = transform.position;
pos.y = a.y;
transform.position = pos;```
that's more efficient at least
The other thing you can do is use an extension method like this:
https://github.com/jschiff/unity-extensions/blob/338d306ba17f86efa7beea1618ef486132e42720/Runtime/Extensions/VectorExtensions.cs#L23
Then you could write the line like:
transform.position = transform.position.WithY(a.y);```
can someone please help me becauese i really dont know why this isnt working?
How do I fix it?
i copied the code from a youtube video and he didnt have any trouble
i just got my unity stuck in an infinite loop because I forgot a yield return null what do i do now
First step is configure your IDE
your IDE is not configured and I can't help you until it is
how?
!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
Follow the guide^
which one shall i click
close and reopen it . . .
wont that lose all my unsaved work
if you didn't save before, then yup . . .
am I meant to follow the whole thing?
Yes
of course
why wouldn't you follow the whole thing
why follow half or only some of it? that would be incomplete . . .
in the unity documentation section I don't have unity API Reference how do I get it?
Now sure what section you're talking about
You just need to follow the steps on the page https://learn.microsoft.com/en-us/visualstudio/gamedev/unity/get-started/getting-started-with-visual-studio-tools-for-unity?pivots=windows#install-unity-support-for-visual-studio
oh - no you don't need this part
just go back to VS
and see if it's working now
See if you're getting atuocomplete and error highlighting etc
I thought you were asking if you needed to do the whole Getting Started part
doesnt work
how to remove it?
It's called CodeLens in visual studio settings
but it's very nice
doesn't seem to work
IDK why you'd want to get rid of it
I know but I prefer it anyway, it's annoying
This looks better now
So back to your original problem, you need to assign your references in the inspector in Unity
really nice, i lvoe it cause sometimes i get lsot and get find where i referenced something and i can just check there
love it
how do i get rid of these errors?
when the guy on youtube did it. it was working fine for him
u kinda forgot to reference ur FixedJoystick
See how you're missing a reference
do i have to assain the reference in the inspector?
lmao
The tutorial guy didn't skip assigning it
I can assure you of that
yes-
What did the tutorial person do?
#fpsshooter #fpsgame #unity3d #joystick
In this beginner unity tutorial we will show how to have a Fps Touch Control with Joystick Asset in fps game
Unity Fps Touch Control are most commonly used in first-person mobile games
Create your own game in 8 minutes
Down...
Do what they did. (although it's possible they just skipped showing it, which is very annoying)
At 6 minutes 25 seconds they assign it very clearly
you skipped that
Don't skip things
bro i did all of this work just for the joystick not to work
Doing half the work doesn't usually work
I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 158
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-4-24
😭
158????
holy
that's probably only one tenth of the true number, if that
These are just the ones I've been online and active to see
now I got rid of the errors how do I get the analog working? I followed the code this time and fixed any errors but still doesn't work
just completely restart i would say
ok
What "doesn't work"
Could someone link me in with a video I should start with on making a main menu, I watched a phew last night and worked on it a little but ran into some errors I couldn't sort out "not home atm but can post photos of said error inna phew"
Whats the point of using this in code? ive seen people use it like this.variable
To refer to this specific instance in cases where it might be ambiguous.
For example:
private float x;
private void SomeFunction(float x){
this.x = x;
}
Cheers 👍
Hi! I'm making a game to teach about the states of water to people with intellectual disabilities as a college project. The game is very simple and has a point and click system (some things about the project are in Portuguese). There's a text saying "Clique no lugar onde o vapor está saindo" (Click on the place where the steam is coming out), and the person needs to click on the pan. After that, there will be another text saying "Clique no lugar que contém líquido" (Click on the place that contains liquid) and you need to click on the juice, and another one will appear saying "Clique no objeto sólido" (Click on the solid object) and you need to click on the ice, then an arrow will appear to take you to the next phase. But I can't make the text dissapear when you click on the pan. There was supposed to be a message on the console saying the name of the object you clicked but that doesn't appear too so I suppose the object isn't being detected
Also the Input Handler and PlayerInput just in case
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
also i recommend using the event system interfaces like the IPointerDownHandler rather than manually raycasting against the objects on your canvas (which really shouldn't have any type of physics, even colliders)
also you've shown a sprite renderer that is not on a canvas in your first screenshot, but you are specifically checking if the object detected by the raycast is a child of a canvas so naturally that object would not fit that criteria
Could you help me do that if it's not too much trouble? I'm a bit lost
well first you need to decide if the objects are even going to be on the canvas or not
No, they're not supposed to be on the canvas
then you need to put a physics raycaster 2d on your camera, then either an EventTrigger component or some component that you write that implements the IPointerDownHandler interface
and that's basically all you need to do in order to detect clicks on an object in the scene (those objects will need colliders too, but you've seemingly already got that)
I put the physics raycaster 2d on it. If I use EventTrigger do I add PointerClick?
Yes, they already have colliders
Should I reference the InputHandler on the object? 
you don't need the input handler. you just need to have a component that will run whatever code you wanted to happen on click in some public method. then you just call that method from this event
You mean I don't need the InputHandler on the camera or I don't need it at all?
you don't need it at all. you don't need to manually detect clicks and then raycast from that. the Event System, Physics Raycaster, and the EventTrigger do all that for you
Oh, I see
all you need is the code you wanted to run in response to an object being clicked on, and that code should be called by the event
Wait but the code needs to be on an object, right?
yes
Then should I create just an empty object in the scene with the script?
Cause I don't need the PlayerInput then
If I got it right
it depends on what you actually want to do in response to the clicking
I just want to hide the text contained in the object cliked and make another one appear
because you could give each of the clickable objects a component that does something in response to being clicked
Well, you need to click on the right object so for now nothing happens if you click on the wrong one
If you're free, I can share my screen on a VC, I think that's easier than just explaining by text
i will not be joining voice chat or participating in any screenshare. you are free to explain what you are trying to do here
Oh, okay. Thanks for your help anyway
I still don't get how to make it work thought
Sorry I asked for help in VC, you sounded really offended
They didn't sound offended at all to me
Just straightforward, which is a good thing imo
Idk, maybe I just got the tone wrong. In any case I'm sorry for any inconvenience
Does anyone know how to help him resolve this?
people will help if they know how (or have the time). you don't have to ask on their behalf . . .
ay yes yes, but the guy there was very concerned about responding by saying "They didn't sound offended at all to me"
they also haven't actually said anything about what they are specifically having trouble with
So what?
Still don't know what I need to add in the camera. And if I don't need to use Input Handler and just an empty object in the scene with the script, you asked exaclty what I need to happened and I need that when the right object is clicked the text will hide and another one will show up
i feel like you didn't pay any attention to anything i told you except to put the EventTrigger on the object . . .
and keep in mind, i wasn't planning on writing the code for you. you need to actually do it yourself
I'm sorry? I just didn't understand exactly what to do? If you don't have time to explain, that's okay. I don't want to be a burden either, I just didn't get it
i already explained what you need to do
No, I'm not asking for that
Okay, if I put the object with the script in the camera what function do I call?
@rich adder
Unloading the last loaded scene Assets/C# Scripts/InfiniteRun/InfiniteRunMenu.unity(build index: 2), is not supported. Please use SceneManager.LoadScene()/EditorSceneManager.OpenScene() to switch to another scene.
UnityEngine.SceneManagement.SceneManager:UnloadSceneAsync (string)
Puzzle2D.UI.Menu/<UnloadScene>d__8:MoveNext () (at Assets/C# Scripts/UI/Menu.cs:70)
UnityEngine.MonoBehaviour:StartCoroutine (System.Collections.IEnumerator)
Puzzle2D.UI.Menu:OnInfiniteRunButton () (at Assets/C# Scripts/UI/Menu.cs:41)
UnityEngine.EventSystems.EventSystem:Update ()
So it's saying you have to have at least one scene loaded
yeah you gotta have at least one scene loaded and active at any given time
oh i see, so basically if i toggle between scenes I can't have multiple loaded at the same time?
if you want to manually manage unloading and loading of scenes, you typically want some other temporary scene to load and activate before unloading the previous scene
you can have as many scenes loaded as you want
You CAN have multiple loaded at the same time.
You just DIDN'T
StartCoroutine(UnloadScene("InfiniteRunMenu")); // Unload InfiniteRunMenu
StartCoroutine(LoadSceneAsync("InfiniteRun"));
this is in the same function that loads the scene. should i not unload it within that function?
You gotta load the scene COMPLETELY before unloading the other
Directing others to a channel is considered cross-posting
crossposting includes posting in an unrelated channel to redirect others to the channel your question was posted in
oh ight thanks lol
You can't have zero scenes loaded. You should only unload the scene when the other one is loaded
or load an intermediary, unload old scene, load new scene, then unload intermediary scene. this is how a lot of load screens work
I'm gonna assume this was supposed to be a 👆
can ayone help me out here im somewhat new and cant seem to figure this out lol here is my errors and this is the script its reffering to using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour
{
//Load scene
public void Play()
}
SceneManager.LoadScene(SceneManager.GetActiveScene().BuildIndex + 1);
}
//Quit Game
public void Quit()
{
Application.Quit()
Debug.Log("Player Has Quit The Game");
}
}
you are missing a ; on Application.Quit()
fyi a single user error sometimes causes multiple errors making you think there are multiple issues in your code .
Look at the lines underlined red in your code and see what's the problem with them
im using visual studio and currently don't see any red underlines?
ah, but there are mulitple errors
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
ill do that right now thank you
fixed that but still some errors ill do th ide thing then check back inna phew min
I realized that, but also I can barely read code in discord
i can post a ss of visual studio if u want
Yep. Once the IDE is configured it'll underline right where the problem is, making it much easier to see what's off about that line. A little bit of up-front time configuring can save literal days of work debugging typos
no red lines, and i followed the ide setup for the Manual install
close visual studio, regenerate project files, then open it again by double clicking a script in your project window
haha no worries can happen xd
Unreal is getting me mad
cant wait to return to my beloved simple and usefull unity T-T
Why is your debug log after the quit code, it’ll stop the code there before sending the log
it won't stop the code. the log will still print
Oh so it’s only for scene changing
no, even that would still work
It won’t
it will. scene load does not begin until the end of the frame
If you have scene change code, anything after that won’t run
incorrect
i can't at the moment. but you could try it and see that i'm right
A lot of people ask why their data won’t save and stuff, and when they show the code they put it right under the scene change line
or read the docs:
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadScene.html
https://docs.unity3d.com/ScriptReference/SceneManagement.SceneManager.LoadSceneAsync.html
When using SceneManager.LoadScene, the scene loads in the next frame, that is it does not load immediately. This semi-asynchronous behavior can cause frame stuttering and can be confusing because load does not complete immediately.
Usually in that case they're changing data on an object that is on the short road to oblivion. If you have it write data somewhere persistent, like to a file, it works
sorry for interrupting you guys but I was wondering bc many people said i should leave the rigidbody.addforce method and switch to velocity. but i dont want to get teleported instantly to my jump height, so how do i implement a smooth jump? should i do it with a curve like how i would write a camera follow script? so the movement gets smoothed out?
Velocity isn't a teleport. It's a speed in a direction. To do a smooth jump, just set your velocity to some upward vector and let gravity slowly decrease it until you start to fall
okay but when i try i get boosted up really fast but fall down slowly. if i decrease velocity i jump less high but at the same speed.
tends to not work with playerprefs but i see the log works. ideally put it before anyways tho
and that can easily be remedied by manually calling PlayerPrefs.Save
attempted. works before scene change
I always use .Save, great for being able to load the data right after
You're probably zeroing out the Y velocity every frame so you don't get gravity
ok im this far do i just do as it says pretty much?
ok i try ty
does anyone know if i can use layers in a similar way to comparetag
basically
No. Layers are a bitmask rather than a hashed string. Usually things that interact with layers are done through a Layer Mask instead of checking manually.
ahhh ok i see
any idea how i could figure out a way to make this work layers instead then?
Check if the layer is the one you're expecting it to be:
https://docs.unity3d.com/ScriptReference/GameObject-layer.html
would i be better off to use this SceneManager.LoadScene("In Game"); rather than this SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1);
Are you trying to load the scene "In Game" or the next scene in the build order?
so its a main menu, this would be for the play button to move to the In Game scene witch would be playing the game, but if i added a loading screen wouldnt it just be for example SceneManager.LoadScene("Loading");if that was the name of said scene
this is currnetly how i have it setup and no errors so far, this would be the start/play button and the quit button
that worked perfectlyyyyyyy thank you all sm
does the new inputsystem mouse delta need to be multiplied by time.deltatime?
No
You never need to multiply a mouse delta by time. It's already a delta since last frame.
So I've been stuck on a code in which I just want to add a limitation to not make the player able to jump middair if he walks off a ledge, because it keeps my "isGrounded" value true. Any clue on how I could do this?
You need to set isGrounded to false when you exit a collider tagged "Ground"
void OnCollisionExit2D(Collision2D) is the method that gets executed when collision with another collider stops
Detecting when you exit a collider for EVERY object isn’t the best, use a ray cast with a layer mask instead.
Both of ours work I was just saying my opinion
Is it one of those cases the answer is so obvious you don't try it firsthand
Yep, basically a copy-paste + changing Enter to Exit and true to false
Man.
But it would be better to use a raycast (or another physics query), the collision callbacks have some flaws, for example if you have two ground colliders aside each other, walking across from one to the other might set isGrounded to false forever if the Exit of collider 1 happens after the Enter of collider 2
Basically what you have for the left/right detections, but for the ground
Hi, how can i show my static var in the inspector ??
Yeah that is indeed happening here, sometimes when I backtrack on the scenario it bugs like that
So I just transform this piece of code to have a detection on his feet?
Yup
You don't. Static variables don't belong to any instance so it isn't rendered on any instances
And instead of setting the speeds on the horizontal input and stuff, I just set it for a tag comparing to enable isGrounded when it is colliding against something with the tag "Ground"?
alright thx
Correct, if you're motivated you could do it on one line, like this:
isGrounded = Physics2D.Raycast(..., out RaycastHit2D hit) && hit.collider.CompareTag("Ground");
Wait 2D doesn't use out params? Consistent much
Well you'll have to do it the long way, like you have for the 2 other raycasts. My code won't work
Is Start, Awake, etc. executed in a unit test?
[SetUp]
public void SetUp()
{
_gameObject = new();
_gameObject.AddComponent<GameManager>();
}
Hello everyone , i'm watching a tuto , where the youtuber ask to do this line
"DrawCircle(Vector2.zero,1,Colour.lightBlue);
But my computer dont know what is DrawCircle
the method have been change to something else recently ?
it is the first thing that do the guy , nothing else have been done before
Writing it just like that means the method must exist in your script or its parent
No what I mean is
This will tell C#, I have a method "DrawCircle" in my class or parent
But if the compiler says you don't, you need to access it from somewhere else
yeah but i dont have script named like this , was thinking about this being a unity base method
I found this, maybe they mean that?
so its not
maybe the guy just skip the part where he made this function somewhere
yeah maybe !
Definitely need to access it from Gizmos I think
thanks for helping
!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.
gotchu gimme a sec
i need help implementing a "dash" that sorta launches the player in the direction they're moving in a natural way (https://paste.myst.rs/mhf38ogv)
a powerful website for storing and sharing text and code snippets. completely free and open source.
i also feel my code is very messy, if you have any ideas on how to maybe make it look better that would be apprechiated
where is the dash specifically? or have you not done it at all
it would be on like 109, but no i have not started it
oh i see
i tried a couple of ideas but they all seemed too artificial
characterController.move seemed like a transform rather than a launch
well with a rigidbody you would AddForce which would make it nice
with a CC idk if there is something similar to that?
im not really sure there is
the closest equivelant would probably be characterController.move()
i guess moving it multiple times over a period of time but a small amount would work
heya, having a lot of trouble with a respawning system i made.
sometimes it works fine, the player takes damage and teleports back to the designated respawn point.
but sometimes the player teleports, takes damage, then teleports again, till they eventually teleport back to spawn
!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.
do i save it and then send?
yeah
do i then send the link?
yeah
the teleport is at the very end of the code
whats meant to happen is that when the player falls off the map, they take 1 damage and get teleported back to the start
ya, ```cs
finalVector =
(groundVector * initialSpeed) +
(airVector * playerSettings.airSpeed) +
(Vector3.up * gravitySim);
if(jump.magnitude > playerSettings.jumpMagn)
{
finalVector += jump;
}
characterController.Move(finalVector * Time.deltaTime);```
i construct a vector before passing it into the Move() function.. for a knockback or something i'd just + knockback.. most of the time it would be 0.. so (having no effect on the move()) but if there was any value there.. it'd just be included in the finalVector..
and then i'd get rid of it.. (lerp it to zero) or set it back to zero until needed again..
not exactly a 1:1 comparison to AddForce.. but it can get the job done
and what happens instead
sometimes the player teleports, takes damage, then teleports again, till they eventually teleport back to spawn
i can capture a video of it
would help yeah
maybe you can use a coroutine.. or an extra conditional. to make sure u've teleported before u take damage
or vice-versa
ive been doing that, ive added a timer to stop the player from taking a ton of damage in the span of like 2 frames
but i'll wait for code to see
Yo
thats only possible if ur damage you are giving is 1/2 a ton 🙃
the player has 3 life
ya, but 2 frames.. is only gonna run (2) sets of logics
i have 10 for the test
I need some tips, im very interested on learning game dev. Some years ago i saw a couple tutorials on how to game a 2d plataformer but i copied line to line so i didnt learn really. I know programming logic and c# basics. I only need a source of where i can really learn unity (YouTube, site, idc)
From where you guys started?
so im guessing u have a fall detection collider down there at the bottom.. and its supposed to set the player back on top?
well a conditional.. if player.y < x
ye ye
ahh i see the file now..
why not
transform.position = respawnPoint.transform.position;
put this line in the update condition u have?
it used to happen instantly, so you went back to spawn with like all your health gone.
but i put a timer on it so you can only take damage every 1 second, and now i can see whats happening better
move the player
deal damage
but if the move isnt working then wouldnt that not do anything?
b/c it would already be moved.. b4 u called damage on it
it couldnt therfor call damage twice.. b/c its still below the threshold
just a thought expirement really
i dont rlly understand this; what are a lot of these variables?
well its weird because it works fin most of the time, it just seams to be that one spot by the corner thats really bad
they're just inputs * modifiers for my directional movement..
say.. i also added + additionalForce... it could be 0 when i dont need it..
and then i could set it to a value (vector) when i do.. and it would jsut get added in w/ the movement its already making..
i get that, im just not sure how this could get implemented within my code
and then the next frame i could set it back to 0 if i didnt need it anymore.. or.. lerp it back to 0.. to smooth it back down to the original inputs/movmenet
its just the concept.. also added + additionalForce... it could be 0 when i dont need it.. of adding a momentary.. extra value to simulate AddForce for example
same way the += jump works.. thats basically simulating AddForce (transform.up * force);
I have absolutely no idea why the Rb2d.AddForce isn't working
using System.Collections;
using System.Collections.Generic;
using Unity.Mathematics;
using UnityEditor.Experimental.GraphView;
using UnityEditor.UIElements;
using UnityEngine;
public class Weapon : MonoBehaviour
{
public GameObject toastie;
public Rigidbody2D toastieRb;
public Transform toastieT;
public GameObject projectile;
public Transform shotPoint;
private float timeBtwShots;
public float startTimeBtwShots;
// Start is called before the first frame update
void Start()
{
}
public float offset;
public SpriteRenderer sr;
public float kbp;
public float Offset = 90;
// Update is called once per frame
void Update()
{
Vector3 difference = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
Vector2 kbd = Camera.main.ScreenToWorldPoint(Input.mousePosition-toastieT.position).normalized*-1;
float direction = math.atan2(difference.y, difference.x) * Mathf.Rad2Deg + offset;
transform.rotation = Quaternion.Euler(0f, 0f, direction);
if (direction < 0 && direction > -180)
{
transform.localScale = new Vector3(1,1,1);
}
else
transform.localScale = new Vector3(-1,1,1);
if (timeBtwShots <= 0)
{
if (Input.GetMouseButtonDown(0))
{
Instantiate(projectile, shotPoint.position, transform.rotation);
timeBtwShots = startTimeBtwShots;
toastieRb.AddForce(kbd*kbp, ForceMode2D.Impulse);
}
}
else {
timeBtwShots -= Time.deltaTime;
}
}
}
its supposed to give knockback after the player shoots the gun
please help im going insane
ignore my sister xd
not working how?
looks fine
oh supposed to give knockback ok
alright i set it up so that it teleports before damage, same issue
because your probably directly setting the rb.velocity in your player movement script
weird.. are there duplicates or anything of that script?
so thats overwriting the force you give it
ohhhh
dont think so
can u add debugs to each part of the sequence to see if anything stands out as odd?
so i could temporarily set velocity to zero?
if you set it to zero then that would give the same result i think?
theres a way around this im pretty sure, but i forgot
i dont see anything in the code you sent that would cause it to glitch like that. unless ur respawnPoint is positioned < than ur threshold
nah its higher by quite a bit
i added an extra boolean.. didnt notice u already had one called.. functionCalled..
but i wonder what would happen if u included it in the conditional..
if ((transform.position.y < threshold) && (timer > 1) && readyToTakeDamage)
i think it might be the velocity cancel out
then set it back to true after u move ur player
so should i just copy and past the code in from that link?
its identical to urs.. i didnt change anything but the extra bool.. so u could
ive been constantly changing mine to try and get it tow work ;-;
but if the extra bool works.. u could remove the timer all together iw ould think
things seam to be acting the same
interesting..
yeah that thing with the functions is the same thing i originally tried
maybe it has something to do with it being a rigidbody
and setting the transform.. manually..
b/c the rigidbody / physics stuff runs on a different timestep
the controller of the ball.. its still running as you do this teleport isn't it?
that culd be an issue too..
Most times people will deactivate their movement scripts -> then teleport the object -> then reenable the movement scripts
this will stop the scripts from fighting each other.. (1 script saying go this way, the other one saying, no do this)
set a reference to the script ur controlling it with..
public MyMovementScript myScriptReference;
then it's like
myScriptReference.enabled = false;
myScriptReference.enabled = true;
thats the same thing as ticking/unticking the checkbox on the component
yup, thats my overall assessment, the ball controller is interfering with ur fall off the map controller
do you want me to send my player controller?
you can but im almost positive thats what it is.. ur using rigidbody / physics.. and it runs on a slower timestep than regular update..
so ur update logic.. is being triggered more than once.. before the physics timestep can actually get around to getting out of hte way..
mhm
how would i add this to the script
or more accuratly, where
just as it is there..
create a declaration to hold the reference..
at the top.. w/ the rest of the variables
TheNameOfTheMovementScript theReferenceToTheMovementScript; drag it into the slot..
and then to enable and disable.. its just
theReferenceTo... . enabled = true or false;
and i put this in my player controller?
no.. you'd need to disable and enable it from the place where ur detecting the when it falls off the map..
if the code is inside the player controller.. and u disable it.. u cant enable it again.. b/c the code cant be run anymore
got it
can't lift a box ur standing in
lol
still doesn't work 😩
toastieRb.velocity = new Vector2(0,0);
toastieRb.AddForce(kbd*kbp, ForceMode2D.Impulse);
toastieRb.velocity = vB;
my script refrence, do i replace that with the name of my player controller?
yeah like i said, you would need to stop your movement by a bool for example
canMove or something, and only set your movement velocity if thats true
and when you do knockback set canMove to false then should work just fine
could you add this to the code i sent, im a bit stumped for where i put it
now that i look at ur setup more and more.. it makes sense ur having problems..
your life script is change the transform.position of itself.. and for that to work.. that also means
that your life script is on the same object.. as the other script controlling it..
so now u have 2 scripts trying to change the transform.. (at the same time)
if u had a reference to the controller.. u could tell it to change its own position (back to the respawn point) instead of having 2 scripts manipulating the transforms together
something like myController.MoveToRespawnPosition();
then it could stop its other logic.. to move.. and then go back to its normal operation
yeah my life script is on the same object as my controller script
which isn't necessarily a problem.. until u have both scripts trying to move the same object at the same time..
the player controller isnt trying to teleport the player anywhere
but it is applying force
no, buts its moving via a rigidbody..
got it
yea, thats also changing the transform.position
alright so how do i fix this
oh sorry i didn't understand
thanks so much!
so you either need to disable 1 of them.. to have the other move it..
or.. you need to have only the movement in the controller itself..
and create a public function that you can call from the other script to tell it to move itself back to the respawn position..
I have this method that tries to generate a random position on the NavMesh, but it does have the slight issue of being kinda likely to run way more into edges than it should, cause it is generating a random position and then calculating the closest point to that position on the NavMesh, so anything outside bounds tends towards the edges. Is there a kinda simple way of preventing this or I just have to work with that? https://gdl.space/avujiponun.cs
well i definitly think there is a way for me to combine both of them into one
i'd say so.. you can probably do all of this inside the ball controller..
since its only detecting if its y position is lower than a threshold..
it could do that itself
should look into how scripts communicate with each other..
b/c the controller could move itself.. when it goes past that threshold. and
then tell the other script to remove the lifecount.. and set teh textmeshpro element..
SingleResponsibility principle
Controller Moves the Ball..
Life script keeps up with the amount of life left..
public functions can be called from other scripts as long as they have a reference..
ur ball controller could have a reference to the Life script..```
// move myself back to respawn
// then tell the life script to take the damage off
lifeScriptReference.TakeDamage(1);```
https://gamedevbeginner.com/how-to-get-a-variable-from-another-script-in-unity-the-right-way/
heres a good 101 type source
you tried NavMesh.SamplePosition ?
Instead of generating a completely random position and then finding the closest point on the NavMesh you can generate a random direction within a given radius around the current position
That's what I did in the code I posted
then sampleposition to find a valid position on the navmesh within that radius
Supposedly, my code is doing a random vector direction from the origin, then adjusting the magnitude within the wanted parameters, then trying to find a position on the NavMesh that is the closest to that, I could find a exact position within the parameters, but then it would miss a lot when near the borders
i'd just sample within the radius.. to ensure points are consistently on the navmesh
yeah i didnt say that the first time my bad, should work easily with this method though
i'd just mess w/ the radius.. soo its not soo big.. that most points are outside the navmesh area
maybe make it dynamic.. depending on how close u are to the edge in teh first place
by canmove do you mean something making the rb kinematic or should a create variable and transfer that over
changing to kinematic is the simpler way.. but could cause unexpected behaviours.. mess w/ other systems
i commonly use an extra bool to wrap my movement and/or input logic in
basically just make a bool and then
if(whateverYourConditionsAre && canMove)
{
NormalMovement...
}
alr thanks a lot
if canMove is false, then it cant move, so it cant set the velocity, so the knockback will work just fine
That depends totally on the player, their positions are calculated around the player position on the time on creating the waypoint
So if they are like purposely getting near corners to mes with their pathfinding that might be an issue
ahh i see.. ya this is jsut basic improvements what u have is default behaviour.. how you can refine it to make it better can go lots of different ways.. but im not big into navmesh so i couldnt say what woudl be the best way to improve it
you could just add some extra checking... like after you get ur first point... run it thru some logic.. see if its close to the edge.. say it is.. get a new point.. if its not good.. if it still is.. try again.. maybe have a cap.. so it only tries X amount of times to find a good point
How can I even get the points on NavMesh that are near edges?
you would get the point first.. via ur calculations.. and then ask if that point is near an edge
Cause I could just add a small offset away from the edge if that's the case
.FindClosestEdge
and the new calculated point.. and the closest to edge point.. and a threshold to ask how close it is..
see, already came up with a good solution
ive changed the code a lot to the point where ive basically had to start over lol
sometimes thats a good thing, tbh
thats b/c i dont know if anyone told u.. but if ur using a rigidbody.. u shouldn't directly change its Transform..
oh yeah i forgot about that
was focused on just mashing the code together
so how do you transform rigidbodies?
you should instead use rb.MovePosition(respawnPosition);
oh!
um.. weird error
"Argument 1: cannot convert from 'UnityEngine.GameObject' to 'UnityEngine.Vector3'"
thats not a weird error
your trying to convert 1 thing to a different thing
which you cannot do
hm, it was working beforehand, changing the transform to a move position caused this?
I promise it did not work before. It could not have. It was different in some crucial way
What is the code now?
what line is this
What is the line number of the error
66,25
your respawn point should be a position
its a GameObject
you cant move to an object
you have to access its .position
oh, alright
which is on a Transform
how would i write that?
you can change the type to Transform or just access .transform.position
i think thats what it was befroe
i have no idea what it was before
but its what it should be now
rb.MovePosition = respawnPoint.transform.position;
is what it is how
thats not what it used to be, it was a bit different, i missunderstood