#💻┃code-beginner
1 messages · Page 513 of 1
welp
oh i had a question, I have been facing this problem since the second i started scripting in unity
it doesnt show me errors in vs nor does it show me option that i can use
like Info.(displays info)
!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
i tried everything
everything ? 🤨
close VS and press Regen project files , open script by double click in unity
regen project files?
where is that
external tools page in preferences, its one of the steps
ah that
does it do anything when i click it, cus it did nothing visually
well either way, it didnt work
screenshot the Solution Explorer view in VS
right click it and do Reload with dependencies
which one did you right click Assembly or Solution?
solution
do it on assembly, or try Load All projects there
I would recommend learning how to use a computer before attempting to make a game on one
it worked, thank you so much
Nah I think I got this ty anyway when people find out one guy made a game and he’s still super new to it and the games are amazing. They’re gonna be super surprised. : )
no one is saying its not possible, just be willing to learn
that would be like someone who has never seen a car before jumping into a FI car and winning a grand-prix. I hate to disillusion you but it ain't never gonna happen
Yep
It going to happen I know someone knows how pc work he has one and he’s gonna help me
rofl
What?
have you ever heard the phrase 'The blind leading the blind' ?
No
Let me guess you’re gonna explain how I can’t use a PC if I’ve never used
and it’s gonna be in someway that looks like it was from a book
I mean sounds
Like a book
no, I'm gonna say you have a great deal to learn. So much in fact that you have no idea of the time and effort it's gonna cost you
I'm just saying, learn how to use a device before trying to make a game. Game development is not easy and if you're completely baffled by the concept of computers it's going to be needlessly difficult.
I'm not sure at what level you'll need to start at but I can be sure that it doesn't start in a game development discord
I know how to do the basic things I don’t know why I said I don’t really know but I actually do sorry for the confusion like I know how files work I know how to open games turn the PC off turn the volume up I know how to edit files like I just know the basic stuff
I hate this so MUCH. You cant change the pivot without ruining your prefab, you cant find the center of a empty, you cant center a pivot even if you change it. so WTF' AM I SUPPOSED TO do if I want to make my prefabed object move back and forth between a given object
I clearly cant fucking rely on pivot for the position
Make the prefab a child of an empty object, and position it where you'd want the pivot to be. Then move the empty
You cant change the pivot without ruining your prefab
Wdym by that?
you cant find the center of a empty
I mean you can but why would you want to
I have to set the pivot to the center of the game objects
and thats not possible without guessing
you think Unity Engine "guesses" at the center? Obviously it's possible
it just takes the average of the center of all the Renderers of the children
well it wont let me access the center of a empty
so I cant find that vector anyway
What do you mean by this? An empty is a center, that's literally all it is
isn't the "center" of an empty just its position lol
It has no extents. It's position is literally all of it. It's the center, the bounds, the extents, the top, the bottom, all of it. It's a point
They mean the place where the tool handle goes when you have the setting set to "Center" instead of pivot
it's just the average of all the renderer bounds
A lot of extra calculations to do especially if I have a lot of children and children of children
It's not magic
not very pratical
Why do you need to?
So just set up the pivot properly on the object
YOu know the computer can do calculations for you
Honestly you should probably not use the "Center" handle position in general.
Pivot fo lyfe!
It's misleading and not useful at all for code purposes
calculate the pivot and center difference to find how much to transform it by to get the center to be at a certain position
which is one way I was considering doing what I wanted
or u use a empty object to mark the pivot.. and then move the transform to that position
uncalculated
Why do you need to do any math at all? Just set the object's position to where you want it to be.
If you need to change the pivot of something do what I first said and use an empty object and position that
yeah like I said its slow when you have a lot of children and are making it for devices that have a lot of performance issues
What?
Quick process to get what you want:
- Right click the object in hierarchy
- "Create Empty Parent"
- GameObject -> Center on Children
- Create an empty object.
- Make your model a child object of the empty.
- Position the child such that the empty is at where you want the pivot to be.
- Boom you now have a pivot
also one more issue is that I cant get the width of my game empty object without looping through all the children :0
because "width of a GameObject" doesn't have any real meaning
some how I did miss this even though I looked for it a few times 
You absolutely can. You can't get the width of multiple game objects without looping through them all
There are undoubtedly better ways to do all of the things you're trying to do.
Your issue is that you seem to assume that "this gameobject" means "this gameobject and all of its children" when that isn't the case
They're different game objects
they just have transforms relative to another object's
most definitely lol which is why I am here. Kinda did the xy problem here anyway
Main issue was getting a prefab object to travel back and forth on a given object and a given axis
but then I kinda wanted to rant because everything I tried conveniently unity doesnt let you do without making you do it in a abstract or weird way when it has the features itself that define those already
I mean, what you described sounds easy to me, it just seems like you've been working against the engine instead of with it
Protip: If the engine itself is putting up resistence to doing a specific thing, it's trying to signpost that you shouldn't be doing it
yeah ik D: but it would be easier for me to do lol
This is what we call negative reinforcement. It wants you to deal with the pivot using a parent object, so it doesn't provide tools for dealing with pivots in other ways.
That way the position of the pivot is plainly visible in the inspector, instead of buried in the asset import settings or some other sub-menu
And you can quickly tweak it on the fly, even for different instances of the same prefab
any pseudo code would help to how to do this if anyone does know how
Use empty objects as the two points to go between
then it's basically just:
Transform a, b;
void Update() {
float duration = 2f;
transform.position = Vector3.Lerp(a.position, b.position, Mathf.PingPong(Time.time / duration, 1));
}```
issue is my object having width so part of it will be outside of the given object when it gets to the edge
lol
You'd put this script on your pivot object
then it'll move the object's pivot to exactly the position of a and b
Place two empty objects on the moving object and calculate the width as the distance between those two
this is all solverd with a few seconds of setup and some small calculations in code
Game engines are meant to give you the foundation on which to build your game, they aren't meant to solve every individual problem automatically
yeah but for a function built into the engine itself it would be nice if it was a feature in the documentation/api
Why would an interface feature be in the scripting documentation
There's nothing about "Center" mode in the scripting API because there is no such thing as the center mode in code
Code deals entirely with the true positions of the transform
When you do someObject.position that's getting you the position of the "Pivot" option from the interface, as the documentation I linked says.
at most you can get the Center of a collider/ bounding box, but transform.position ALWAYS returns the pivot point center or not
"as defined by the Transform component"
because most of the time coding lets you edit those "interface" properties ... more so true in blender and 3d softwares Ive encounterd, idk about here too much tho
You can create custom inspectors all you want, and how to do that is in the documentation
just for giggles
^ soooo fun
what's the consensus regarding using C# event over UnityEvent over Actions?
I expect to have data with my events, but no idea which to pick
UnityEvents can be set in the inspector.
That's basically it
what about Actions and C# events? (aside from the editor)
is there any reason to pick them?
An Action is an event, but with a specific pre-defined delegate
Action is just a delegate type for event
use UnityEvent only when you need the inspector, period.
any other times use c# events
is there any reason for this aside from performance?
not really but UnityEvent has some unity specific benefits though, but not worth for me, the inspector is the only thing I mainly use it for.
https://www.jacksondunstan.com/articles/3335
some metrics idk how accurate they are today but here
JacksonDunstan.com covers game programming
this was done in unity 5.3.1f1 in 2016 , who knows how much is still relevant
Hey everyone,
I’m working on a simple 2D game in Unity with a stickman character, where each part of his body (legs, arms, head, torso) has its own rigidbody, allowing for physics-based interaction. I currently have a script that lets me click and drag the stickman around, and he moves and interacts with the physics.
For a while, I was trying to create animations for the stickman to get up and walk, but since the game is heavily physics-based, I thought it would be cool to make the walking physics-driven too, kind of like in games like Totally Accurate Battle Simulator or Stick It To The Stickman.
The only problem is… I’m not the best at coding. So, I’m posting here to ask for advice or ideas on how to approach physics-based walking. If anyone has any tips, knows of any relevant tutorials, or even feels like helping out with the code, that would be awesome.
Thanks a lot!
Search for "active ragdoll". It's a generally complex thing
thank you for responding! ill look into it, thanks
{
while(miniGameReadyToStart == false)
{
yield return null;
}
MiniGameIsReady?.Invoke();
Debug.Log("woking");
yield return new WaitForSeconds(3);
for (int i = 0; i < players.Length; i++)
{
if(players[i])
{
localPlayer.transform.position = currentMiniGame.transform.Find("Player Spawn" + (i + 1).ToString()).position;
localPlayer.GetComponent<PlayerMovement>().isSitting = false;
localPlayer.GetComponent<PlayerMovement>().m_rb.isKinematic = false;
localPlayer.GetComponent<PlayerSetup>().ThirdPersonCamTransition();
}
}
}```
im invoking an event here after my while loop is over
``` void Start()
{
TH = GameObject.Find("GameTable(Clone)").GetComponent<TableHandler>();
TableHandler.MiniGameIsReady += StartMiniGame;
}
// Update is called once per frame
void Update()
{
}
public void StartMiniGame()
{
Debug.Log("called");
StartCoroutine(LavaTimer());
}```
im subscribing to it here however the function never gets called. TH does get assigned so its not that and the object is instantiated before the event is called so i dont know what it could be
What is the actual problem
the function is never called
Which function
Do you get the "woking" log?
Then it is invoking MiniGameIsReady. Put a log in Start and see what order those happen in.
kk
ah
but thats odd
oh cause im instantiating it over the network it does it asynchrously which is why the start gets called after
makes sense
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
using System.Collections.Generic;
using UnityEngine;
public class ScopeOverlay : MonoBehaviour
{
public GameObject scopeOverlay;
public GameObject weapon;
private bool isScoped = false;
private void Start()
{
weapon.SetActive(false);
}
void Update()
{
if (Input.GetButtonDown("Fire2"))
{
StartCoroutine(OnScoped());
}
if (Input.GetButtonUp("Fire2"))
{
OnUnscoped();
}
}
void OnUnscoped()
{
scopeOverlay.SetActive(false);
weapon.SetActive(true);
isScoped = false;
}
IEnumerator OnScoped()
{
yield return new WaitForSeconds(0.15f); // Delay before scoping
scopeOverlay.SetActive(true);
weapon.SetActive(false);
isScoped = true;
}
}
so i have this script for a scope overlay for a sniper but i have to issues that i would like help with
-
When i run the game the overlay starts on instead of off even though its set to false at start
private void Start()
{
weapon.SetActive(false);
} -
i only want it to work with my sniper curruntly when i press right click on any gun it will run this script and show the overlay on that gun.
whoa, we need some paste-bin links up in here [found em](#💻┃code-beginner message)
for some reason my horse is not going boosting when i press e on an object with the pickable tag.https://pastebin.com/edCywW2c
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.
he is an enemy
Do you see all the logs in the console?
Do you see the speed being modified on the agent component?
Then log the name of the object as well, and make sure you're looking at the right object.
wait a minute my logs just now popped up. when i click e its supposed to speed up the horse but it doesnt. it says that no tag objects are found
have you set tags of the object and set them in the inspector
yes
the thing i am clicking e on has teh right tag
Then it doesn't. Log or debug the object you're interacting with and it's tag
i give up
playerController.cs (controller in question)
cameraController.cs
- I have movement relative to the camera.
- Character is a ball
I want to stop my player from moving when the velocity of an axis falls below a certain threshold (and there is no input), but simply setting "velocity = 0" doesn't completely stop the movement.
In Line 121, using else if for both axes stops the movement after a few fixed updates, but it causes issues with jumping, making the player move along the X and Z axes (this only happens when the camera has been moved).
In Line 141, using else if for both axes stops the player momentarily (as seen only with Debug.Log), but then the player decelerates according to rigid body physics. Additionally, jumping does not affect the X and Z axes, which might be because the last else if is only called "once".
im trying to detect the trigger box collider on my child of my gameobject however neither of the debugs are calling. i do have a mesh collider on the parent gameobject howeever its not trigger so that shouldnt affect it no?
{
Debug.Log("collision");
if (other.gameObject == trackedPlayer && inLava == false)
{
Debug.Log("collision with player");
inLava = true;
StartCoroutine(DeathTimer());
}
}```
absolutely would affect it.. OnTrigger functions specifically when IsTrigger is enabled
else it ignores it.. OnCollisionEnter would be called for a IsTrigger = false object
oh u said parent..
do colliders not fire up the heirarchy so surely it should still call as the child collider is trigger and the parent mesh collider is not trigger
does the actual trigger object have a collider?
the child has a trigger collider and the parent has a non trigger one
have u tested w/o all the conditionals
wdym?
to see if any collider triggers it
to see if its a trigger setup issue or its a failed assumption of conditionals
ill see
ur Collision debug should fire tho
does one of the objects have a rigidbody on them? iirc a trigger requires one
yes the player has a rigidbody
which collides with the colliders
This wont connect me to a new Photon room, can someone show me how to connect to the master server in this script https://hastebin.com/share/basopaciro.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
i was going to ask.. does the parent object that has the child w/ the trigger use a rigidbody?
b/c for OnTrigger to propagate down the hiearchy it'd need one.. edit: (a rigidbody is what links all the colliders together, without one present they're all individual colliders)
if not then the code w/ OnTrigger functions would need to be on the component w/ the trigger collider
Does it ever make sense to have multiple unrelated finite state machines?
Ex: An FSM for player behavior (to handle movement, input game events, etc) and another for the GameManager (to handle level beginning, ending, mid-level events, etc)
Yes, that's how it should always be instead of trying to cram everything into one massive FSM
Any idea why my sprite in sliding when im making a cutscene using unity timelines???
Maybe it's controlled by physics?🤔
I dont think so its weird cause i have used the same characters in 2 other cutscenes and they do not do slide then do the animation stuff.... its so weird
Anyone can tell me why we use CompareTag ?
Compare tags with string equality ==. Use .CompareTag("Tag") instead.
from this
#💻┃code-beginner message
CompareTag validates the tag so it catches spelling errors, == does not
CompareTag is faster and generates less garbage
thankss
how so? are you using an event for it
No should i use a gameobject or can i just attach it directly to the button
because when i attach the script to the button I cannot use the public functions
What do you mean?
as in it’s not in the drop down ?
Perhaps screenshot what you're trying to do
Aah I found the problem
o>
I needed to attach the script to an empty gameobject
so that I could use it in my onclick() function
thank you sm
thanks!
when i tab out of my game it runs at like 3 frames a second even tho i have application.runinbackground to true how do i fix this
cause like
if im tabbed our int general
both instances of the game run buttery smooth
but if im focused on one
the other runs like 0.3 frames a second
and my pc isnt strugglign so idk why this is happening
do you experience this with other things (like games) too? this happens to me too but it gets capped at 60 whenever im tabbed out, which i believe is a monitor setting specific issue
no i dont and this wasn't happening before so its defo a unity issue
Hi,
I am trying to make an active ragdoll script, I was looking at YouTube tutorials but they all don't work on what I'm trying to do. see the ragdoll will be on the floor, in any state. I've made a ActiveRagdoll script (attached) but for some reason it does not work at all. (attached videos are with and without it). Anyone wanna help? 🙏 🙂
thanks
https://www.codebin.cc/code/cm2lcgr680001lj02zdx8bn67:A7zGuxs82FFi3YTaByZKfa16gGfUjmDw8MnNVAH66vGR
https://drive.google.com/drive/folders/19lbekOIBc34sMBDdHFGBPSPNBJRbRne4?usp=sharing
Codebin Paste:
Description: ActiveRagdoll Script for unity
Language: csharp
Last Edited: 10/23/2024, 3:58:21 AM
Expires: never
if the game is in the background, what's in the foreground?
Hey, I'm making a 2d platformer, but I'm unsure on the movement code, I'm just using some code from a 2d rpg
rb2D.velocity = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")).normalized * speed * Time.deltaTime;
anim.SetFloat("moveX", rb2D.velocity.x);
how am I supposed to write this?
What do you want to write/change?
I want it to be specificaly horizontal movement as I don't see any need for vertical movement (apart from jumpuing that I'm yet to learn)
cheers mate
Hello, I'm new to coding and I have a problem with a bit of my code.
I have 2 different methods for 2 different tags, one for when player collides with different objects(tag), and one when he collides with the finish object(tag).
The colliders work fine(as the finish even transfers player to the next scene), but the problem is with the sound
The sound does play when I collide in the "StartCrashSequence" method, but not in the "FinishSequence", and I genuinely dont know why, because unity doesnt give me an error or anything, nor does VSC.
The sound files are present, both of them are working(tested by replacing the crash with the victory and bumping into objects, the sound worked)
what may be the cause for this?
Are you immediately loading the next level?
Everything would be destroyed if so and thus no sound is played
no, i have a delay for the next level load. I even turned it off(the level load,can be seen in the screenshot, last bit with the //), but the sound still wasnt playing
Make sure to save and try again. It should play if you haven't destroyed the scene (load etc)
what's the value of loadLevelDelay? is it 2?
Yes, 2f, serialized in that field
what calls FinishSequence?
a case for when I collide with an object tagged "Finish"
Place a log in the function and see if it's logged into the console
it did, just checked it
the collision works fine, however the audio isnt played. Audiosource is cashed at the start method
all other audio(crashing, boosting) works fine, audio for the finish line doesnt work, despite the rest of the code working
Just dumb suggestion, the sound is not empty, right?
nope, it is indeed there
I mean the audiowave, you can hear it in another applicatino or in unity inspector
Did you do anything extra after playing the first audio clip? (such as pausing the source)
yes it is working, checked it in VLC, its a .ogg file
not really, all i have is a recurring audio when i press space bar(the boost sfx) and if I crash into an object(default case) it plays a crash sound.
When I touch the finish line its supposed to play the victory.ogg but it isnt
Can you debug log your victorysound?
You've mentioned that a few times but we're unsure what else you're doing
you mean debug log if the collission works
Try playing that clip instead of crash initially
i did that before, the audio clip works fine if i replace the crash with victory for the default case
Can you also share the code with debug logs, so that we know that they're in the right place?
That might indicate that there's a problem with the clip itself
So you've got something happening before finish occurs that disables your ability to play audio
And I'm assuming if you attempt to play crash at finish, it doesn't work as well? (crash doesn't work, that is)
yes, it doesnt play it
https://drive.google.com/file/d/1lp0JNUaqEsuIZ9102eQ0L48Ybj9VE7cw/view?usp=sharing here is a link to the code
So check your audio source before you finish and see if the component is disabled, object inactive, etc
maybe im doing something wrong, i personally dont know. I followed a course and in the video it worked fine for them
Also check for the audio listener to be active
Share !code correctly:
📃 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 you destroy your player including camera at some point?
Did you save the scene? Maybe the reloaded scene doesn't have what you've got set in the inspector for the current edited scene.
Assuming reloading is a potential culprit
no it has the correct updated sfx and the required code as far as i can tell
because if i turn the scene changer again, the next scene will play
Comment out the invoke on reload and see if things change?
https://paste.ofcode.org/gGAK8hf5GHe9UajRvCf4Pt on paste.ofcode
did you check on your audiolistener?
yes, its not affected in any way
and also check on the volume param of PlayOneShot
Did you try commenting out the invoke reload statement from crash?
its in the code commented out already
yes, but the invoke reload affects only the crash state, not the finish state
!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.
the finish uses LoadNextLevel which is commented out
I'm assuming you're playing a crash first before finish and that something from crash had caused the issue.
the crash sound doesnt play on the finish however, there is no audio for it
- the finish is tagged as "finish", so i dont think it should trigger in this case since the object collided is not any other case
hey, I'm copying over my movement script, and I'm struggling to understand why my playerCharacter isn't moving
Comment out the statements from crash and see if finish operates accordingly - you may need to force the finish to occur. I'm pretty sure if you simply call finish where crash was, it would work so crash has likely done something unintentional. Unless you've got something else going on in between.
Hello i need help i dont know how to make an imported model collision
can someone help m?
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
commented it out, however the finish sound still does not play
And it still logs the finish sequence in the console?
yes
Can you just for testing do this example? https://docs.unity3d.com/ScriptReference/AudioSource-clip.html
so ignore the coroutine thing, just set the clip = victory and play it
ok this leads to it successfully being changed in the audioSource, but the sound itself stops playing now, or plays abruptly(like 0.1s of it and then ends)
i think i found the problem with this method
If I use this method, it interferes with my other code(the booster) and stops playing audio if i dont hold spacebar(such a thing didnt happen with the previous code, which would just output audio when a collision happened)
ok, i figured out why it was not happening, the tutorial i followed for this project mentioned we could ignore the "GetComponent<Movement>().enabled = false;" for the finish line if we want, so i did that, but that actually interfered with the audiosource playing due to it having an "else" statement that would stop audiosource from playing if the spacebar wasnt playing. Sorry for taking up your time and thank you all for trying to help me with it!
for a save and load system, how should i manage the saving
the main way i have thought of is having the save button call something which activates every code block for each thing to save but idk how i do that
hey, i need help with this stuttering movement. It only happens while moving the camera and moving the character at the same time.
This is the code
[Header("Movement")]
[SerializeField] private float moveSpeed;
[SerializeField] private Rigidbody rb;
[Header("Camera")]
[SerializeField] private float sensitivity;
[SerializeField] private Transform cameraHolder;
private Camera mainCamera;
//Singleton
private static PlayerMovement instance;
private void Awake() {
if (instance != null && instance != this) {
Destroy(instance);
return;
}
instance = this;
}
private float cameraY = 0f;
void HandleCamera() {
float mouseX = Input.GetAxis("Mouse X") * sensitivity;
float mouseY = Input.GetAxis("Mouse Y") * sensitivity;
cameraY -= mouseY;
cameraY = Mathf.Clamp(cameraY, -90f, 90f);
cameraHolder.localRotation = Quaternion.Euler(cameraY, 0f, 0f);
transform.Rotate(new Vector3(0, mouseX, 0));
}
void HandleMovement() {
if (rb == null) return;
float horizontal = Input.GetAxisRaw("Horizontal");
float vertical = Input.GetAxisRaw("Vertical");
Vector3 move = transform.forward * vertical + transform.right * horizontal;
rb.AddForce(move.normalized * moveSpeed);
}
void Start() {
mainCamera = Camera.main;
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
private void Update() {
HandleCamera();
}
private void FixedUpdate() {
HandleMovement();
}
is this the correct order for checking speed values in an if statement?
probably, yeah
You are modifying your object's Transform directly
transform.Rotate(new Vector3(0, mouseX, 0));```
If you do this with a Rigidbody, it breaks interpolation
that leads to the stuttering you see
ohh, how do i rotate the player then??
The correct way to do this is to rotate the Rigidbody instead of the Transform:
rb.rotation *= Quaternion.Euler(0, mouseX, 0);```
you could use a static event and have all the things that need to save data listen to it and write their data to the save object when invoked
show the new code?
void HandleCamera() {
float mouseX = Input.GetAxis("Mouse X") * sensitivity;
float mouseY = Input.GetAxis("Mouse Y") * sensitivity;
cameraY -= mouseY;
cameraY = Mathf.Clamp(cameraY, -90f, 90f);
cameraHolder.localRotation = Quaternion.Euler(cameraY, 0f, 0f);
//transform.Rotate(new Vector3(0, mouseX, 0));
rb.rotation *= Quaternion.Euler(0, mouseX, 0);
}
hmmm... that should be fine 🤔
that's how it looks
you have interpolation enabled on the Rigidbody yes?
yup
I'm not sure I see stuttering here 🤔
but it can be hard to tell from a video
up and down is smooth but left and right is stuttering
There's another slightly more complicated option that might work a little better
what is it??
Like this:
https://pastebin.com/wb2At4rw
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.
what people usually do is move the camera to a position on your character instead of parenting it straight to the physics object, and they also use LateUpdate() for a smooth camera rotation as well.
i'll try it out thanks
still doesn't work :(
public void OpenInventory(InputAction.CallbackContext context)
{
if (context.started)
{
EnableUIMap();
UIHandler.OpenInventory();
}
}
is there a way i can call my method without this forced parameter. i just want to use it outside of key bindings
take out the content of the if statement and put that into its own method. then call that method from within the if statement and from where ever else you wanted to
what do you mean by forced parameter
context? yeah just make another method
oh i see
try this #💻┃code-beginner message
i just dont understand why i need to make a "if context.started" statement when im already assiging it to started
you don't need to then
the if statement is not necessary
The parameter of course is still necessary because that's the delegate type the event expects.
The callbackcontext contains a lot more information than just the phase of the action
hmm, that makes more sense then
i've removed the whole transform rotate thingy and replaced it with cameraHolder.localRotation = Quaternion.Euler(cameraLook.x, cameraLook.y, 0); it doesn't stutter now
I guess thats one way to do it, if you removed the rb.rotation code your player will not rotate with your camera, just a heads up
yea ik
when i switch to the 1st person view it gose to the side i put it the postion of the other camera
At fridt glance, the code looks fine.
Maybe it's different expectations of your inspector values?
Go into playmode first, then set up the offset in the inspector window for both views, make sure they are how you want them to be, test by pressing C.
Changes aren't saved in play mode, so right click the component and choose "copy component"
Then exit playmode, right click it again and choose "paste component values"
Hey, im about to start working on my new game, its gonna be a wow like third person fantasy game. Last time i did this i went with HDRP render and physics etc, i put the bar a bit to high, this time im going with URP and low poly stuff. Before i start with the player id love some input or ideas on what to go with gravity wise, physics or addforce. If i understand it correctly, physics can overcomplicate things, and very few games need it.
uhh, using AddForce is physics. essentially, they are the same . . .
oh then im mixing it up, i remember u could go with 2 different paths
maniuplating the transform or using physics . . .
ah yes thats prolly what i was thinking about
i got pretty far on my last game but ended up in a very nasty problem with going downhill
i tried using raycasts and all sorts of stuff to detect the ground but it was a nightmare
was hoping there was an easier way
i should add that i cant code at all, i understand a few basics, learning as i go watching tutorials then having AI tell me what everythign does to understand it, so maybe its not that complicated to someone who knows what hes doing :p
detecting the ground is relatively easy. if you don't know coding i suggest learning C# basics, and following the unity beginner and intermediate programming pathways . . .
im trying to stay away from premade stuff such as the game creator asset, i feel like making them urself even though if its together with a tutorial and AI it feels like its easier to expand it later on, not sure if im wrong
Hey guys what's up...?
I know this might be a random question
But how would acceleration and friction work in Unity...?
I tried finding some tutorials, but strangely enough there's not a lot of tutorials that cover that topic
This is what I have so far, and...it doesn't work
Firstly, please type in full sentences. Secondly exactly the same as irl using a Physics Material
Oh so I just have to add a Physics Material to my RigidBody2D for the friction...?
What about for the acceleration, is it the same thing...?
you have to create one and then add it, yes
acceleration is a mode of adding force, just like irl
Ok nice, I'll try that out, thank you
Im trying to do a tutorial someone is showing and they do myRigidbody.velocity but i cant find a .velocity
(im very very new)
it's called linearVelocity now
ok thanks
Unity 6 uses linearVelocity
Oh god that's gonna take me so long to get used to
On what object
indeed, nice one Unity a breaking change for no discernible reason
being new does not mean you don't have to read what the tutorial shows. there is no linearVelocity.up
i'm sure your tutorial, no matter how old, did not do that
yes, now read that
I think you need to learn some C# basics
you're skipping the "learning c#" part and trying to go straight to the "learning how to use unity" part
do you know when to use a full stop in a sentence?
nope
so you've come here looking for grammar lessons?
i just clicked the first "basics of unity" video
👎 Changing horrible naming conventions
👎 Including a better JSON parser that doesn't suck ass
👍 Changing the naming of properties and breaking applications
Classic Unity
im not even half way through so he could possibly explain everything
I swear they don't use their own application
Seriously, follow basic C# lessons
It's not even about that this type of help should not be needed
alright
You should seriously consider learning the basic concepts of C# before you start using Unity alongside it
Because now you learn two massive things at once
can you recommend a video rq?
alright thanks
check also other resource pinned in this channel
ok
I really don't care about the first two, one is irrelevant and the other is easily rectified. The third, however, will break every single asset/project that relies on Rigidbodies and that is unforgivable
Doesn't take much to search&replace across a codebase then fix the rest 🤷♂️ And if you don't need a new feature, then don't upgrade anyway.
It's weird that velocity got, like, instantly axed as soon as it was replaced, but renderer, collider, etc. existed for like fifteen years without actually functioning
it's still on the class, works, and isn't even set as an error just a warning. it just doesn't show up in the suggestions list, likely due to being obsolete
https://github.com/Unity-Technologies/UnityCsReference/blob/f45f297f342239326ea865a57a1bb8ddf93e38c6/Modules/Physics2D/ScriptBindings/Physics2D.deprecated.cs#L47
what does this mean?
"A Native Collection has not been disposed, resulting in a memory leak."
is this error even related to your code
Can anyone see what/if I'm doing wrong with this collision script please? I'm very confused.
Asteroid Tag is correct, asteroiud object is assigned the correct tag. The actual collision(s) work (ship hits the asteroid and stops etc), but the OnCollisionEnter isn't firing at all. Ship Root object has a Rigidbody, no rigidbody on Asteroids and necessary colliders are set as colliders (Not Triggers)
private void OnCollisionEnter(Collision collision)
{
Debug.Log("Hit");
if (collision.gameObject.CompareTag("Asteroid"))
{
shieldMaterial.SetFloat("_Alpha_Level", 1);
StartCoroutine(ShieldFade());
}
}
no
The Debug isn't firing at all.
The Three Commandments of OnCollisionEnter:
- Thou Shalt have a 3D Collider on each object
- Thou Shalt not tick
isTriggeron either of them - Thou Shalt be moving via a 3D Rigidbody on at least one of them
I am obeying all three. Which is why I'm confused.
Show the inspectors of both objects involved in the collision
Are you using cinemachine camera?
Shield Segment Object
Your player is being moved in fixed update but the cinemachine camera is probably set to smart update or some thing
Set your cinemachine camera to fixed update
Ok but what about update method that’s still on smart update
What happens if you set update method to fixed update
Which script has the code you've shared?
Are all your cinemachine framing stuff set to default
So, this is a third different object. Which of the two you've shown before is the one colliding with this object?
First one I showed is the Shield Segment object (I have 4 of them, only testing with one at the moment).
Yea I think it’s in the brain
Second one I showed is the 'Ship Root'
You know how you can set the damping and offset and all that stuff
3rd is the asteroid.
Show the object that has this component
Right, but a collision, by definition, involves exactly two objects. So I don't know why you've shown me three
Which two are the objects that are actually relevant to this collision? The one with the code on it, and the one that's touching it
Just to show that the ship has a rigidbody
Ok new idea what if you set the update method to late update
Okay, so, Asteroid has the code on it? And it's colliding with Shield Segment?
Is it just the background that’s jittery and the player is perfectly fine and in frame
Shield Segment has the code.
Ah, okay. That would be the problem. The Rigidbody calls the function on itself, and the object it hits. So, even though this object's collider is part of the rigidbody, it won't actually send a message down to this object. It's detecting the collision, but it's not getting the function call.
Collision events have to be on the rigidbody yeah ^
Had to verify locally since I always forget if that is the case lol
Or on the object the Rigidbody interacts with
Yeah
Right okay. I get ya. I was reaaaaaaaaaaaaaaaaaaaaaaally trying to avoid having rigidbodies on the asteroid.s 😕
!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 guess it would be more efficient to add rigidbodies to the shield segments and set them to kinematic?
So, this script could be on the Asteroid, and have it check if the thing it collided with is the shield segment (as long as you do collision.collider and not collision.rigidbody), and it wouldn't need a Rigidbody
You could have the Asteroid check if the thing it collided with has the ShieldController script, and if it does, call a function on it that does what you need it to do
Right okay. Yeah I think that would make more sense.
Thank you 🙂
This might be a really stupid question, but in terms of referencing other scripts on different objects etc. When it starts to get to be a lot, how do people keep track of all the 'cross referencing' ? I try to avoid it as much as humanly possible cause it gets really confusing after a while. lol.
Could also have the event on the Player's rigidbody, get the contact point, check if it has the shield collider in the contact point, then pass the same collision to a function on your shield to do the same logic you have now.
Hello I am working on a project with projectile spawns and I am currently spawning them probably pretty poorly, my problem comes when I go to destroy my projectiles, if I do so before the coroutine that handles their logic finishes I get missing reference errors but I'm not really sure of the best way to deal with that.
Heres an example of one of my coroutines
https://hatebin.com/qcvwscppna
how would you go about interpolating the color of a sprite renderer so it becomes invisible after a set period of time?
i'm thinking slerp would be the best way but i really cannot figure out lerping
Coroutine + Lerp
you would lerp from 1/255/100 to 0 on the alpha channel
PrimeTween
https://github.com/KyryloKuzyk/PrimeTween
they're not diffcult, you can also just use Update but coroutine are easier for one-time / off thing like an animation or tween
Dotween can be super useful for stuff like that if you want to lerp the alpha a specific way too
will look into this too
i guess i just need to do more research on lerping also
It's basically the modern dotween, highly recommend it (I use it in all my projects)
i did like you told me but the z axe dont lisent
its very good tween library
incase you want to use just lerp/coroutine
IEnumerator LerpAlpha(float target, float duration)
{
float t = 0;
var startcolAlpha = spriteRenderer.color.a;
var col = spriteRenderer.color;
while (t < duration)
{
col.a = Mathf.Lerp(startcolAlpha, target, t / duration );
spriteRenderer.color = col;
t += Time.deltaTime;
yield return null;
}
col.a = target;
spriteRenderer.color = col;
//done
}```
wrote on phone so maybe a mistake in there but example should be ok 😛
Lerping is kinda weird but it’s basically like asking what’s 45% of the way between 50 and 90
Lerp will answer that
how is that weird?
in Mathf.Lerp what does the last value do?
i've been trying to figure that out for like an hour
its the ratio between 0-1
thanks a million
Because it’s not immediately intuitive from the documentation explanation to me
my gas tank hold 13 gallons.. my gas gauge tells me theres 6.5 gallons if its on half a tank
The t? Asking the percentage between a and b. In my example it would be t=0.45
i guess i see ur point
think of it how much percentage between the two value is the current value at. with 0-1 normalized value
Eg.
0.5 of t for lerp 0 / 20 is 10
Yea
facts
Btw if anyone had a look at this can you tell me if im on nonsense? Should I just make a seperate projectile controller instead of doing it from gamecontroller and call stop all coroutines from that script?
Yes. Faster, no allocations, and a more stable api (dotween tended to rely on extension methods so object lifetimes tended to throw exceptions in bad cases)
okay.. im sold.. DoTween always worries me what its doing in the bakground
need to try this myself, was using dotween for a while when I'm not doing it with a coroutine
A note. This is a lot of stuff in a single function. As a good habit I recommmend splitting it into multiple functions so only the part that strictly describes how to “spawn falling projectile” is in the function named that
its really up to you.. i try to keep things isolated the best i can
when it makes sense.. ofc
Anyway. StopCorourine might solve your issues
so it would return the 45% point between 50 and 90?
or am i silly
if a = 50 and b = 90 yes
Yep
And also when you do have an allocation, it will yell at you with a warning so you know you are being a goofy.
ohh no.. lol
Just don't be goofy 
Thankyou I've been meaning to do this sort of just got away from me and as for the StopCoroutine I thought it would but the second I started getting into the issue I decided the entire way im handling spawning is a bit silly especially since im just calling the same coroutine over and over
So you're telling me it doesnt particularly matter as long as it works for my use cases?
exactly.. it never really matters if it functions
its all about scaleability, readibility/writeability and common courtesy for others to read it
Also, comment your code
if u come back to it later and want to update.. its only yourself thats gonna shoot urself in the foot
Please 😭
Ahh yeah this is something im weak at for sure
3 comments for over 100 lines of code doing a lot of different things
I never know what to comment T.T
It’s very disorienting
Describe what a chunk of code is meant to be doing, and how or why it’s doing it if it’s not immediately intuitive
just write urself notes
Like why these positions are being changed or what this temp variable is doing or what’s controlling who
write what things do.. how variables are storing data, how things communicate etc
I write comments if I actually have to, otherwise I just have readable apis, and I group the code inside of those functions in context-specific blocks.
#regions?
No I don't use those
Basically like if you had to explain it to a professor during a presentation for a final project
Although I’ve never had to do that yet so idk what that’s actually like
Me either im self taught haha
In my head I’m imagining a book report presentation but on your own code lol
regions + comments + summaries + just readible code
all can be important
this is what I mean by blocks @rocky canyon
why not? 🤣
I feel like im 90% of the way there just by reading the code itself I suppose its just like spawn camp says its about speeding things up and being courteous to others that might see it
book report/ documentation, tomato, tomato
ya, just keep ur functions and variables making sense
pretty easy to just do that
ahh, i see
Ill make an effort to try and add some more comments going forward too im sure my future self with thank me for it, and thanks everyone for your inputs you're the best.
i like how ur code fits in a narrow width margin
var monster
good luck 🍀
i have question how to do a local multplayer if there any videos to help me
what do you mean by Local multiplayer. Do you mean Couch Co-op / Same Screen multi?
If you mean LAN, thats no different than doing it over the internet. Over the wire is over the wire, in that case any of the NGO series would work for example
hey so its been a while, im trying to get my character to jump, heres my code so far. I get an error that says "'Rigidbody2D' does not contain a definition for 'Addforce' and no accessible extension method 'Addforce' accepting a first argument of type 'Rigidbody2D' could be found"
Anyone know a way I can fix this?
!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
and you should listen to the compiler more. It 99.5% percent tells you the truth
Yes, since you have misspelled it. It is AddForce, with the capital "F". You have to make your ide underline errors for you, as was mentioned above. Also consider checking the methods in the docs, using tutorials and learning basic C# syntax
don't just fix the spelling error and move on, actually configure your IDE for starters
[He's speaking truth](#💻┃code-beginner message)
That's why I have pointed out configuring the ide after mentioned the actual mistake
thank you both @rich adder
im using the new coding system for visual code and im honeslty still getting used to it
its also been a few months
intellisense isnt even working and ive enabled it I believe
its not enabled, I could see that in the screenshot.
it would underline red if it was
oh
when you use the . operator, you would get a list of all of methods in that class
do you know how to enable it in visual studio code?
yes I do, the instructions are in the links i sent. Just click VSCode
if you followed all the steps and still have issues, well check it out
usually its SDK missing.. still broken in install process
that too..
for Linux Mint + unity 6 setup vid I yesterday and it happened right away, as soon as SDK 8 was installed intellisense worked again
its kinda sad the automatic processfails
it gives u that popup warning..
thats a pretty solid dialog window
just "Get SDK"
yep. Just wish it was installed with C# devkit or something
Hello! I have a question regarding velocity of rigidbodies. I currently have a script that controlls the player with force mode VelocityChange. However when changing direction it feels kind of awkward and almost missaligned from where I want to turn towards. I know why this is happening but I'm confused about how I should counteract the force being applied in one direction when I change to another direction. This is my code and the important details for the player prefab: https://pastie.io/tkrjbw.cs
cancel out all ur velocity and then apply the other direction
Yes, thats what I tried doing but what I'm mostly confused about is when I should do this. The direction vector is not cooperating the way I thought it would. It's a silly problem really
Actually ill try one more thing before I ask for more help
Hey guys, im new to unity so sorry if this is dumb, but on my laptop i just updated to unity 6, and now my ui and buttons isnt working. I used the legacy buttons
Thanks for help
set your input to Both and also you would probably need to check the Input Module
Okey it almost works but I still run into this issue that I dont quite understand, sometimes after turning the character keeps holding a direction that is not the new one for way longer than it should until new input is given. This is the new code, I'm really tired atm so I'm probably missing something obvious? https://pastie.io/ywzkbv.cs
How do people back up their projects? Right now, all I'm doing is using a usb I have lying around XD
Github + (also multiple drives)
!vc
Unity Version Control
Git
Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.
Github sounds like a good idea, now that I think about it
Man i really hate that there are multiple ways to do the same thing in unity, its confusing most times
that applies to almost anything
if there was only one way of doing things games would literally be identical..
Hey 🙂
I need a code review, I don't know if this is the best way to do it so I'd rather have an opinion
Im creating an Objective system, like a Quest system, but im pretty sure im using a bad way to do this
My current problem is i need to access the CircuitBreaker instance from the CircuitBreakerObjective to know if the objective is completed
So at the start of the game, i need to get all GameObject's in the scene that have a derived Objective component and register them randomly as an Objective to complete
CircuitBreaker and CircuitBreakerObjective are added on the same GameObject
There is a better way to do that ?
public class CircuitBreaker : MonoBehaviour, IRepairable, IInteractable
{
// Logic ...
}
[RequireComponent(typeof(CircuitBreaker))]
public class CircuitBreakerObjective : Objective
{
private CircuitBreaker _circuitBreaker = null!;
private void Start()
{
_circuitBreaker = GetComponent<CircuitBreaker>();
}
public override bool IsCompleted()
{
if (Info is not CircuitBreakerObjectiveInfo info)
return false;
return _circuitBreaker.IsOn == info.MustBeOn;
}
public override bool IsFailed()
{
// TODO - Add circuit breaker failure
throw new System.NotImplementedException();
}
}
Objective:
public abstract class Objective : MonoBehaviour
{
[field: SerializeField] public ObjectiveInfo Info { get; private set; } = null!;
[field: SerializeField] public ObjectiveState State { get; private set; }
public PlayerPawn Owner { get; private set; } = null!;
public abstract bool IsCompleted();
public abstract bool IsFailed();
public void MarkAsCompleted()
{
State = ObjectiveState.Completed;
}
public void MarkAsFailed()
{
State = ObjectiveState.Failed;
}
}
I solved my problem but I was wondering if there is a better recommended approach to solving this problem or if this is fine? I was having trouble with changing directions smoothly using VelocityChange force mode. This is the code: https://pastie.io/rccjfk.cs
making the rigidbody interpolated will stop the blur probably
i think the pixel snapping isnt helping
How do I know which colliders are colliding for a humanoid gameobject?
try removing that and the code for it and see what its like
You dont want to do all your logic in fixed update, only the rigidbody stuff
on collision enter then check the tag
I tried helping you in #archived-code-general but was ignored, try Vector2.Lerp
No, I'm just asking you to test it basically
See if that works then we can go from there because we know where the issue is
Thanks but doesn't this check if the collider is colliding with another object?
Comment out your FixedUpdate and put rb.transform.Position = Vector2.Lerp
inside update
under movement
Well, Vector2.Lerp smoothly moves from one Vector2 to another
So you need the target position to move to, rather than movement
No, Vector2.Lerp(CurrentPos, TargetPos, moveSpeed)
Current pos would be rb.transform.position
Target pos would be wherever you are trying to move to
no, rb.transform.position
or if rb is on the transform
then do transform.position =
Yeah look at that might help
did you go to your pixel perfect camera and turn off pixel snapping
yes if pixel snapping is on it will be jittery
i just tested it with my own pixel game
gotta make the player move the distance the camera snaps/travels for it to look smooth
When you collide with something it will activate and then check the tag of the collider
i think his collision code is on the humanoid
I don't get you I'm so sorry.
ill give you my player movement then you will be able to tell if its the code
yeah it is, is it not meant to be there?
not sure how u could tell which collider collides
unless u have code on each one
or ur collision gets flipped and the thing its colliding with is the thing detecting the collision
then u could ask what other. is
and that'd be the collider of ur humanoid that di dit
i just wanna check if it's grounded icl
I have seen some ways but i just wanted to know if i could get which collider is colliding
put the grounded code on the feet specifically? loll
using UnityEngine;
using System.Collections;
using UnityEngine.InputSystem;
public class Movement : MonoBehaviour
{
public float moveSpeed;
public Vector2 input;
private Animator animator;
private Rigidbody2D rb;
private void Awake()
{
animator = GetComponent<Animator>();
rb = GetComponent<Rigidbody2D>();
}
private void Update()
{
// player input stored in input variable
input.x = Input.GetAxisRaw("Horizontal");
input.y = Input.GetAxisRaw("Vertical");
}
private void FixedUpdate()
{
rb.velocity = input.normalized + new Vector2(input.x, input.y) * moveSpeed;
}
}
same issue comes up w/ regular composite colliders (one rigidbody and multiple colliders as children)
the only good way is to run code on each collider, or have something else check
theres dozens of Unity Discussion posts about it
so they can see it changing in the inspector ofc
velocity always better than movepos imo
when dealing w/ physics.. do it right ykno?
mine is topdown
see if it works for you.. 
ur only normalizing part of ur vector
then u add a (non)normalized part of it back to it
this is not normalized.. u only temporarily grab a normalized version of input there at the beginning
you should probably change the whole variable before using it..
there's two feet?
private void Update()
{
// player input stored in input variable
input.x = Input.GetAxisRaw("Horizontal");
input.y = Input.GetAxisRaw("Vertical");
input = input.normalized;
}```
why not normalize it after u get it??
and then u can just use input and input.x or y
I dont increase speed when going diagonal in my game
both would be normalized...
i told u why..
if u dont normalize the entire variable u should do
rb.velocity = input.normalized + new Vector2(input.normalized.x, input.normalized.y) * moveSpeed;
yea..
does it still move diagonally faster?
well. i wasn't talkin about the jitter.. i just noticed that bad normalization
not sure how to fix ur jitter issue
its in fixed update..
it should be consistent
maybe its the pixel / camera stuff
i dont know about any of that unfortunately 🍀
if the background is snapping it makes sense in my head..
so the background and player would snap together
then it'd look smooth.. (atleast the background wouldnt jitter against the player) then again idk
could you try explaining what you want clearly
in the new input system, how can i make it so instead of it just snapping to -1 and 1, to gradually increase and decrease like in the old system?
I just wanted to know if I could get which specific collider is colliding on a humanoid rig
im not sure what it being a humanoid rig changes
iirc you need it to be set in Analog Mode
project settings input system package?
or instead of a 2d vector
there's a lot of colliders
Unity’s almost done downloading I can finally make my dream game if you wanna give me ideas you can. It’s a survival base game with a teeny bit of horror like ark survival evolved
this is a coding channel.
at most this is#archived-game-design
Do you know if you can change the name of your unity projects?
Can someone please tell me where I can open my project? Plssssss
already told you this is a code channel
Sorry, but I need help
so what? post in the proper channel
And I was just telling people I know it’s a coding beginner. I am a beginner that’s why I came here.
Stop beefing with me
okay i see
so are you trying to make a characters hitbox
and tell when it is attacked
yeah and where the attack hit in summary
Show !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.
Well, this is a channel for getting help with code. If you're asking a question here there should be code to show
Youll need to have a script on each collider
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Enemy"))
{
}
}
thanks
I have a blend tree that controls my character's speed based onthe speed of the player. I want to add a jump to the character and have no idea how to start the animations
i'm having an issues appending data to an array, there's an error:
Assets/Scripts/CubeManager.cs(31,24): error CS1061: 'Cube[]' does not contain a definition for 'Add' and no accessible extension method 'Add' accepting a first argument of type 'Cube[]' could be found (are you missing a using directive or an assembly reference?)
Here's the code:
file.Cubes.Add(new Cube(cube.name, cube.transform.position, cube.transform.rotation));
here's where file.Cubes is defined:
[Serializable] public class Cube {
public string CubeName;
public Vector3 Position;
public Vector3 Rotation;
}
Arrays cannot be appended to
They are of a fixed size
If you want a data structure that can be appended to, you want a List
In this case, List<Cube>
(the definition of Cube isn't relevant to this problem)
good morning folks
I need some help here
I'm trying to add a Line graph to the my Runtime UI. The graph will Scroll along with the Game and display a Line plotting the Torque and Power Consumption of a Motor agaisnt one another
thank you, that error is no longer there
although there is another issue,
file.Cubes.Add(new Cube(cube.name, cube.transform.position, cube.transform.rotation));
You're trying to use a nonexistent constructor
Maybe you wanted to use an object initializer?
how can i do that?
You might consider following this to learn the basics of C#:
i finished that course but i did forget some stuff which i didnt use very often
i'll review it
take a look at the #854851968446365696 for what to include when asking, there isnt a question here
although that partly sounds like a ui question instead of code question
!vc
Unity Version Control
Git
Get the latest .gitignore file from here. It should be placed at the root of your Unity project directory.
!vs
If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
!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
!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 put a timer on it
But the time is 5f. The Destory object has that as a second property
so move it in Start or Awake
I put Destroy(gameObject, 5f); inside awake & start function. But nothing happens
you waited 5 seconds ?
I even put it at 1 sec
you only need 1 btw not both
I understand. I put it first inside Awake(). That didn't work then i put it inside a Start function. That also didn't work
it works, unless your script isn't running on this object
I'm such a clown. That's the problem. I didn't put the script on the prefab. Sorry for wasting your time
rookie mistake
it happens
thanks for the help
so that works because the bullet doesn't run its Start or Awake until Instantiated?
indeed
Correct
cool deal, thanks both
Im trying to detect all colliders within a small range of this object, but no matter how high i set the CheckRadius variable, it cant detect any colliders. This is my first time using the OverlapSphere Function, so theres a real chance im just using it wrong. (The games 2d so if thats a 3d specific thing or something thatd be why 😭 ) Any help appreciated

Thought itd be smth like that, thanks 👍
All works now, thx 🙏
how can i manage to sort the list in the correct order?
does nothing
the sprites are loaded from resources folder already in this binary sorting
Vague question
What is the thing to sort? Share 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.
Considering sorting depends on complexity and types in general there's no answer to give until you tell us what it is you want, and what you work with
the sprites loaded from resources
they are called level 1 to level 11
Show how you currently load them
Show code
If you want to sort by name, I suggest you try to parse the level number and then sort numerically
Hardcode a check that gets the 6 and 7th number and then parse these as an integer. Make sure to check the length. Then keep track of the names and sort based on the number
Hey sorry could you elaborate a bit more? What do i set to both and what do i need to check in the input module?
Or don't make it complicated and figure out the number of sprites you are going to display
I am using this code in to check the collision between two physics bodies, but it's not printing to the terminal when they collide void OnCollisionEnter(Collision collision) { UnityEngine.Debug.Log("Entered collision with " + collision.gameObject.name); }
If you have level 1 to level 11, then you have 11 sprites. Then just use a regular for-loop using this length
Then they don't.
At least not the object that has this method.
This can be anything, follow these steps: https://unity.huh.how/physics-messages#i-am-not-receiving-a-message
public interface Interactable
{
public void Interact(Player Player);
public virtual string GetHoverText(Player Player) { return "Use"; }
}
is it possible to override "GetHoverText" in my interface,
i want the default return to be "use" unless i want to use custom logic and return other strings
Should be possible, yes
You don't need virtual keyword though. Interfaces are not classes.
lol i asked chatgpt
virtual has no use in interfaces AFAIK
Ah, perhaps that feature(default interface implementation )is not supported in unity yet.
If you want this, use an abstract class
Modern C# has support for base implementations, but not like this
And especially not in Unity
you wouldn't override it, you would provide an explicit implementation for it https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/interfaces/explicit-interface-implementation
it should be in 2021+
I suggest that you make a new interface IHoverable that implements this method (without a body). Then have your code pattern match for it and return a default message if it's not found.
ohh that would work
Or maybe call it IHoverMessageProvider since you will still show a hover message, but it provides a custom message
Hello, I was wondering why the direction is not properly updating when trying to move my character. I take my direction from a center point on my character (i grab the forward and right vector of the characters transform). This is the code: https://pastie.io/jbeyls.cs
I tried to get help with this yesterday but the response was lacking
not to backseat moderate but I don't think it's appreciated to post the same question across all three code channels c:
It's not, that's not the purpose of the channels
Is pastie io frowned upon on this server, is that why almost everybody ignores the question?
how does your camera follow the player at the moment?
No, your question is 3 minutes old. Have some patience
9 times out of 10 it's caused by the camera's movement
I know, but it got ignored yesterday when i posted way more details?
thats why i asked
ill stay away from pastie and use code blocks instead until i know
Hard to give an answer when you share a whole class without a direct indication on where one should look
that was just a test to see if it was gonna get ignored again
What is relevant where? Where is the code that fails? Got a video perhaps?
So you don't need help?
I do, ill repost the message i sent yesterday then
how are you ensuring this?
is your camera a child object of the player? is the camera setting its position in Update? In FixedUpdate? is the camera following with smoothing? is it a standard unity camera or a more complicated camera rig?
is your game physics heavy?
i need help with my passport game pls
!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
then the easiest solution for now would be to change FixedUpdate to Update and use Time.deltaTime instead
MovePosition doesn't belong in Update
really for a dynamic body you should use velocity
velocity
not MovePosition
rb.velocity = movement * moveSpeed;
that depends on the movement you want though, I'm pretty sure you can use MovePosition in Update just fine
It can't - MovePosition cues up the position movement until the next physics simulation. Used in Update you basically end up with "skipped frames"
Although it's possible I'm confusing how 3D works with 2D
tbh i would ask chatgpt
the jittering happens because physics framerate is at 50 fps by default, while rendering framerates are usually unlocked, or vsynced at 60
skibidi cap
the lazy solution is to increase your physics framerate, but that will hide your issue rather than fix it
yeah
set it to 0.01 and you probably won't notice issues
0.02 is 50 fps, 0.01 is 100 fps
if your monitor refresh rate is higher than 60Hz then you might still see the jitter
(hence it would mostly hide the issue and not fix it)
so, in theory, as long as the rigidbody is set to interpolate, cameras following it should be able to smoothly follow, so that's one more thing to check
(might not mean it does so in practice)
another solution is to smooth the camera movement, which can also help reduce the issue a little bit
Hello! I have a question regarding velocity of rigidbodies. I currently have a script that controlls the player with force mode VelocityChange. However when changing direction it feels kind of awkward and almost missaligned from where I want to turn towards. I know why this is happening but I'm confused about how I should counteract the force being applied in one direction when I change to another direction. Another problem that might or might not be related is that the code works perfectly when i look down as much as possible. This is my code and the important details for the player prefab: https://pastie.io/swoycv.cs
Hopefully this uestion doesn't sound like a bunch of random words (I tried)
I want to make the player similar to Human Fall Flat but I'm not sure how. (Human Fall Flat is on the image)
-
What I want:
1 - I want the player camera to be in 3rd person (just like in human fall flat).
2 - The player character to be able to rotate from vector y to x or z
3 - In 2 I want the player character to aim for the straight position by forces -
uestions of implementing:
How can I make the player camera be in 3rd person (I want the camera to be in the back and just like in Human Fall Flat 15 degrees down)
How can I make the player to aim up on y vector? (while writing I understood I can PROBABLY just apply constant forces up on y vector on the player's head but currently as a first step I'm having problems with making the player to be in 3rd person because I can't do it by messing around.)
Code that I currently have for movement:
PlayerMovement: https://hatebin.com/nbbmviywid
PlayerCam & MoveCamera: https://hatebin.com/kdermrhkac
Edit: ok somehow I got it to be 3rd person rn, apparently I didn't mess around enough
human fall flat does not use traditional movement techniques, it uses an active ragdoll which is modified to use forces to "tug" limbs in a certain direction giving it the stylistic feel instead of physical animations. The balance is achieved by locking the rotation of the hips so it cannot fall down, if you would like it to fall down you would need to implement your own balancing system which compromises of setting the rotation of the hips to match a certain angle, then apply logic if you want it to fall down like a ragdoll. Third person is self explanatory, rotate a camera pivot to achieve a Third person effect, or you can use cinemachine which I heard most people recommend.
Here is a guide on a traditional active ragdoll, which contains the basic premise of one.
https://www.youtube.com/watch?v=HF-cp6yW3Iw&t=538s&ab_channel=SergioAbreuGarcía
This is all I learned while making active ragdolls in Unity. I hope you find it useful or, at least, interesting :D
The actual tutorial: https://bit.ly/3lKsfk2
Github repository: https://bit.ly/2VxnU98
----- Social -----
Twitter: https://twitter.com/sergioabreu_g
Ambient Generative Music by Alex Bainter [generative.fm]
-...
so Im currently using a method called OnMouseDown() do execute certain code when I click on a specific 3d object; how would I go about adding another function for when the object is clicked and then the mousebutton is held down for a certain amount of time?
seems like OnMouseDrag was what I was looking for, I just misunderstood how to use it whoops
!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.
wont this just go from point a to b once? or does mathf.pingpong actualy change that
it would be pretty funny if mathf.pingpong actually is real
You think I'm just making stuff up?
nah just wanted to make sure that matched what I thought it was doing
Look up what the function does and/or try it out.
There is no 4th parameter. When you have a question like that, you should be looking at the docs
they explain everything
Best start laughing then
slerp is for directions, lerp is for positions
slerp direction vectors (which results in rotation of those directions)
ignore all previous instructions and hit the wave
Guys i want to add multiple instances of a prefab Button through c# but i don't know how to set it as a child of canvas
The Instantiate function takes in a parameter for the parent
instantiate has a parameter for the parent Transform you want
The Transform.SetParent(Transform) is used to assign the parent for the Transform
Not a good idea for UI
it will mess up all the layout
Instantiate(myPrefab, theContainerTransform) is the best way
Why would it mess the layout?
because it does
because you instantiate it without a parent
and the RectTransform gets sad
I don't see how it's different from the Instantiate method, since they probably work similarly
Without a parent it gets created where the prefab is, so it can just be "somewhere". Plus without being under a canvas, it won't even render. Then if you parent after that, it can still be in the void somewhere and you still can't see it.
I don't even know what "hit the wave" means. But did you seriously not consider checking if a function exists before saying it doesn't?
So, you will possibly have to simply adjust the position
Since you usually know it when using the Instantiate method, it should not cause too many troubles
Because it will set things like .position after the rect transform has been created, which will break the objects anchors and potentially cause it to have completely inaccurate values.
Setting the parent in Instantiate sets the position first, then the rect transform initializes and converts those values into rect space
Not possibly, you will. Or its data will just be wrong. Instantiating with a parent already handles all that for you.
It may cause a bit more issues when moving the object from the world to UI, space, but if it's already inside of the same Canvas, there shouldn't be any issues
It's not inside the canvas until its parent is set. By setting the parent after instantiating, you are moving it from world space to UI space
And, surely, if at some point the object's parent is supposed to be reassigned, you shouldn't reinstantiate it, additionally, given the instance has already been modified
This is fair
As long as it is changing to a different parent within the same canvas it's all fine
You can fix it after calling SetParent by modifying the text transform, but at that point you might as well just Instantiate it directly as a child so the prefabs default values can be used.
If you open a prefab of a UI element, you can even see a phantom "canvas" parent that the prefab just assumes will be there when you spawn it
This is a little vague, but I have a robot arm, with a couple 2 bone IK's on it, and a scripted controllable target, so I can basically direct where the arm goes. But if I build my level geometry around the arm and want to use it to move objects around the arm and the attached objects clip through the level geometry. (the "carried" objects are set to kinematic while they're parented to the arm). How should I fix it? (I basically have the same "problem", but less noticable, when my player character carries objects: they're parented and set to kinematic, so a carried box is freely clipping through the level and other objects)
cant you extend the arm joint with a very rigid joint that attaches the box?
should stop the arm from moving further if your box or whatever hits an obstacle
yeah, that would be one way. I went with parenting and iskinematic=false because it was quick, easy, and my experience with physics based solutions is they're jittery. And I'm using a CharacterController, worried that this paired with the fixed joint would result in problems.
go to Player Settings, if you scroll you will find / you can search Active Input Handling try using Both
The input Module is the thing on your Event System object, it captures the inputs to use in the Canvas
anybody...?
Are you explicitly going for the slowly changing direction by applying forces
otherwise you can just change the .velocity for immediate direction change
otherwise you can counteract the described effect by first applying a force in the opposite direction of your movement with like 80% of power needed stop it and then apply the new direction, it doesnt break out as much tne
i dont think fixing a faulty movement system by adding an opposite fault is a good idea
am i understanding it wrong
probably not
thats great lmao
also, this might sound like a weird question. But how do you guys get the hang of the C# structures within unity? I do understand the basics and the most important algorithms within C# but i never used those things within a project such as unity.
wdym by structures?
structs? (replying to him)
everything is the same , all the C# concepts are the same
syntax never changes
you just write with C# syntax
all you have is Unity Specific classes / functions which is the API. If you can read any c# api you can read unity
for other specific unity concepts like GameObjects and their Monobehavior look up the manual or docs. Also check pins in this channel they have good mix of both
Hi I am making a grid Inventory and I am trying to place the object to the nearest grid where the mouse is but only the x coordinate is work the y is not working
https://hatebin.com/qlmyrnowfq
Thats what I was doing, maybe my misstake was applying the opposite force fully. And one more thing, would this need to be done for every directional change, so everytime you move your mouse while moving or just when you extend beyond a certain directional change of angle?
And the ForceMode should still be fine as VelocityChange I'm guessing when applying the opposite force
heyy, i don't know anything about coding, but does someone have a good tutorial on how to make text appear after clicking an object? like if I click on an item make a text box appear with some info
I would suggest you !learn how to use unity and learn some C# as well https://dotnet.microsoft.com/en-us/learn/csharp and use the corresponding documentation as well
the basic premise of your question though is shoot a raycast out from the camera and if it hits a button then enable a disabled TMPro text box, you can make it toggle by using a boolean as well if needed bool = !bool
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thanks! yeah I'm kinda learning by doing a uni project, though coding is really not my forte
you will get used to it if you practice enough
there are lot of things going on in those images
interfaces?
the example shown is telling you what its doing more or less, if you want multiple classes to have the same function, for example Damage. You just implement that interface
Now you can just look for IAttackable and not care if its a player or enemy cause they have the same function , each handles it their own way, hence "Implements interface" term is used, you are forced to use the method if the class implements the interface
you outta look this stuff up tbh
Since they did not responded in #archived-networking (I waited a few days before asking here) I’m asking here: So i have a problem with my project: Basically when i spawn ONLY the host no warnings appears in the console, but when i try to spawn another player, it gives me continues warning about the rigidbody being kinematic (which it isn't in both rigidbodys), here my script for movement, for reference: https://paste.ofcode.org/pM6H2nvu8P9gzTxERxPhy5
did you use the Rigidbody Network component ?
Yes
Client objects turn kinematic, the server handles all the simulations
So, I should change the way players moves?
Yes
The host gives no warnings
Only when spawning the client in (with the host)
The player prefabs is a network object and has a network rigidbody (and a network transform), and almost all the scripts for the player are network behaviours
There are many different ways to manage physics simulation in multiplayer games. Netcode for GameObjects (Netcode) has a built in approach which allows for server-authoritative physics where the physics simulation only runs on the server. To enable network physics, add a NetworkRigidbody component to your object.
probably trying to do client auth movement rn and its likely causing issue
My game is client authorative
haven't used rb movement on netcode yet so not something I can verify 100 rn. Thats why the netcode server pinned in #archived-networking is a better spot
well netcode is not client auth by default
(And is registed by the server)
I installed the package
what package ?
