#💻┃code-beginner
1 messages · Page 349 of 1
That happens every frame. Time scale doesn't matter
Update happens every frame and doesn't care about time scale
FixedUpdate is affected by time scale
a vector is simple, 2 floats
got it thanks, got a little brain.exe stopped working moment
omg nope. I'm just an Idiot, there is a return statement, but its made it way ALLLL the way down to the very bottom of my code, I don't even think its within the Mesh constructor
new… new input system????
oooh okay so this is how you bind the prefab to the variable ?
moveDirection = (transform.TransformDirection(Vector3.forward)*currentInput.x) + (transform.TransformDirection(Vector3.right) * currentInput.y);
How does this line return 0 on the y?
yes there is a "new" and better one, not so new anymore though
gotta look into that now
I mean moveDirection is a vector3 but we only deal with x and y input?
because moving forward would be on the z
put it on the actual gameobject that has the script
okk yea i did it
Like What I dont get is, moveDirection (vector 3 with 0,0,0) then we do the equation and = vector2(0,0). What I'm asking is that where the last float is
it would become 0
you dont set it to a Vector2
but we only work on 2 inputs on the right hand?
your only giving it a X and a Y from your Input, however your putting that into a Vector3
your not directly giving an X and Y to moveDirection
it could be simplified as transform.forward * currentInput.x + transform.right * currentInput.y too?
since im not touching the remaining axis it remains as it is which is 0?
debug.log moveDirection and see whats the result
I'll do that once I get home. On a different pc at the moment.
not exactly reamaing what it is.. it'd get set to 0
if its at 0 then yea its the same..
but if u set it a Vector3 to Vector2 the last property gets set to 0..
<#💻┃code-beginner message> heres the code if you havent seen
yea i was about to scroll
ahh okay coolio
I was just confused how we assign vector2 to a vector3
A little synthatic sugar I often use myself, maybe you guys would like it-
Make a few extension methods like Vector2.X0Y(), Vector3.XZ(), Vector3.X0Z() and stuff
The function is self explanatory
Thanks for the help
It simply adds the z axis with 0, sometimes get me by surprise
normally if you do
Vector3 = 2, 5, 5
Vector2 = 0, 2
Vector3 = Vector2
``` then the result should be `0,2,0`
Similar thing with using a vector3 as a vector2, it throws the z axis away
yup
Btw guys, what would be the best way to create some sort of cancelable event?
if I want to permit layers of subscribeable functions that would block something from happening
The best I have is delegate with a ref bool
I was like where the hell is the third number that is 0
or the bool
Good to learn now thanks all.
Just a bool reference? No better way?
im sure theres other ways. but thats the first thing that comes to mind..
I saw that delegates can pass something back. What would that do?
ya, u can have a sender parameter
Uh, I mean, can that in any way be turned into a true if any subscribers return true thing?
Ooh I see now. transform forward * currentInput.x is lets say 0,0,5 then we add + transform.right * currentInput.y is say 6,0,0 then the result is just a total of 2 3Vectors added. Thats how It does not throw an error because y is 0 in the end
Goddamn
and also because moving forwards and backwards is the z axis x is left/right and y is up down so wouldnt make sense to set y to anything based of movement
We would just go up in the air then right?
yeah
and about erroring, it errors if you try adding a Vector3 TO a Vector2, but not the other way around
yeah cos the example you provided says that it leaves it as it is but if its the other way around the last float doesnt have anywhere to go?
yeah, just trying to add something that has no where to go
Well great. Thanks a lot!
where can i ask about unity installation itself?
Hi I have problem with buttons in canvas. I can't click on it and I have no idea where is problem.
Do you have an event system in the scene
Is WordEventSystem an EventSystem you've renamed and attached other objects to? Show the inspector for it
So do you have an event system in the scene
No?
Then that would be your problem
So how do I create it?
Create -> UI -> Event System
And that is everything?
yes
you might need to click the big red button on it if you're using the New Input System, or it might have come with one. If it doesn't look angry at you that should be enough
Nope. I installed new input system and still not working
hey, in my folder script I have the class A and the class B, and now in my class C i want to instanciate them but from what i understand, I really need to drag and drop the A and B to the inspector ? Why isn't it as simple like using or import idk ?
Show your event system
Are you trying to create an instance of a normal class or Instantiate a GameObject with a component on it
just a class
new ClassName() works fine
he just say the Type or namespace name 'A' could not be found, I wrote Using A since its in the same folder
(vscode does not help alot on imports lol)
Please help me. I'm solving this problem over a hour and still it is not working
Do you have a namespace named A
just public enum A nothing really special
At the bottom of the inspector for the event system there is a window that shows information about the interacted UI elements, including what is hovered and selected. See what that is saying is under the mouse when you hover your button
Using statements are for namespaces. Do you have a namespace A?
no, so i should use another keyword like import ? Im from java idk much about c#
You should just use the class
If it's not in a namespace it's global
okok i see
No it is now working. I replaced with normal legacy button
Is this a good way to do it?
public CanSlotModifyDelegate CanSlotModify = (Itemstack it, int i, ref bool b)=>{};
I have to initialize it with a starting value cus otherwise += would throw a null reference exception, I'd not use = cus again, it's meant to be an event to subscribe to.
If it's an event you should use the event type
https://gamedevbeginner.com/events-and-delegates-in-unity/
Well, not exactly an event ig, since it's also used as a question by more than just itself...
*Called by other scripts too
Strange, they didn't initialize it but they're implying that it works without.
hey there! does anyone know if there is a way to check for when a variable like a float reaches a certain % of it's assigned value?
let's say i set a float value in the inspector, how can i check when this value reaches <= 50% of it's value no matter what i assign for it as a value? any help would be greatly appreciated!
So give this object a public function that invokes the event, and call that
Why though
do i just do something like * 0.5 for 50% and such or is there a specific better way to do it?
InverseLerp gets you the percentage a value is between two endpoints
Is marking it as an event going to avoid the issue?
So you can use event and take advantage of all of the syntax that C# provides
Eh, tbh, thinking about it, I might as well for another reason
Cus this nightmare
bool canceled = false;
CanSlotModify.Invoke(itemstack, i, ref canceled);
if (canceled) continue;
Delegate implements the + operator in such a way that the left hand side can be null, so it doesn't need to be initialized. This is entirely for convenience.
Strange, that should mean that CanSlotModify += ToolBar.CanSlotModify should work without any issue
Uhm... Imma test it again to prove my point... Or prove that I did a blunder even if I'm skeptical of that one
Answer iiiiiiis... Yes, half
Non-event delegates/actions/funcs will have trouble with += when you haven't assigned a value to it
But adding event does indeed bypass the issue, soo... Thank you digiholic xD
Sigh... No it's mistaken, event appears to be unable to bypass the issue 🤦♂️
edit: No wait it does actually work with or without, am I the one who did a blunder all along??
thanks sorry was in a meeting for ages, before i try moving the scene. I am goingto try ddol, but it dos not become a ddol
DDOL wont prevent the other objects from being deleted if scene is unloaded hence the Missing reference, You either don't unload the scene or you'd have to bring the enemy objectsnested inside their own root DDOL, probably more of a hassle
Thanks i went with wrapping a game object around the battle scene and moving it to a new space and not unloading the main town thank you for your input was really helpfull
Hi, I'm working on a game that requires players values to change based on duration of time passed.
There are time difference calculations, calculated between the player's current time, and a previous timestamp stored on a remote database.
What are the best practices / frameworks to use for getting the player's current time from the Internet? Essentially, I don't want the player to change the time on their device to speed up time durations. Whenever a CurrentTime is called, I want the player device to check the CurrentTime of some cloud service.
Is there an existing web service / function in Unity? Otherwise, what are the standard ways to achieve this?
If you're making a multiplayer game or something of that sorts, pretty sure you should simply never let the player send it
Never trust input from the client, basic rule
Checking for time should be done by the server in that case, I guess
You would operate/run a web service/web application for this stuff
Kind of a whole different skillset/toolset than Unity
Timezones can still trick it I think? Though it'd be so constrained that it'd not be very valuable... Normally.
did you already setup auth ? cause thats probably your first /most complex step.
Unless if he's trying to make some sort of highscore/shortest time beaten system
Idk, no matter how I think about it it can be tricked
I heard that clientside's encoding doesn't work cus they can use your program to do the same
yes everything should be handled server side, client just sends request
ideally to an API
Basically that means that if people want, they can have full control over the whole client
Which then... Ig that the only way is to announce that you've started a session, and then... No, even then they can fake the victory signal
this is why everything is mostly handled with tokens
How so? How does that make it safe?
because the token was issued by the server, usually with a custom signature
if you tamper it, the signature doesn't match , becomes invalid
So... The token acts as a key to the session on the server, I'm guessing?
yes hence why they typically have expiration time
you the dev have to handle the timing and refreshing new tokens to keep someone logged in
What stops cheaters from using the token to send fake data back though...
Currently I'm imagining one of those speedrunning games
We already have an auth system and cloud save system. But that tool does not have such a feature to give the current UTC time.
DateTime.UtcNow
store that inside each players Cloud Save
they would first need your token somehow
some tokens also add machine signing , depends on algo used too
If hackers can use the whole client's stuff I don't see what stops them from using the token ngl
Doesn't "DateTime.UtcNow just convert the device's time to UTC?
if you have someone backdoor on your machine you have bigger issue than game cheating score
no dont you want to save the player time you said?
I meant moreso that I dont want players to be able to set their mobile device time to some time in the future, to skip ahead the time they need to wait for features in the app
This is what i'm looking for a solution for. Sorry for the confusion
No I mean... Like, for example, my brother actually did some modding on a multiplayer game before, he could just access the client's source code...
yes then you need to grab non-local (machine) time
you need to grab server time
just make a simple HTTP Request to some free server time
are there any standard APIs that game devs typically utilize?
World Time API: Simple JSON/plain-text API to obtain the current
time in, and related data about, a timezone.
Or any Unity time server service offered?
You can make a cloud code module
but probably not worth wasting tokens
Oh great idea
true
When there are free solutions out there, got it
Ok thanks for the help!
soo many
Hi I'm trying to use the Meta Movement SDK examples, specifically the Aura Sample, to implement a handtracking and eye tracking logger (print positions of user's hand and eye movements). I'm not really sure which scripts to modify and how to get this information. Would appreciate any help for a beginner at Unity! https://developer.oculus.com/documentation/unity/move-samples/#face-and-eye-tracking-with-aura
Provides an overview, instructions, FAQ, and other information about body tracking for Movement SDK for Unity.
a friendly noob has appeared!
hello!
today i learned about the component system lol
good thing too, unity is Component based
why does velocity.up work but velocity.right doesnt? i cant move right?
I don't see velocity.up or velocity.right anywhere here
show the inspector of your object?
i can jump but i cant move right
did you constrain the x position of the rigidbody perhaps?
(also what's with the weird brackets)
yep you constrained the x axis
oooh
omg
maybe you meant to do rotation ? 
why doesnt this event show up?
because it's private
and doesn't have [SerializeField]
so it is not serialized
BUt also... a UnityEvent wouldn't show up in that list in the first place
only methods will show up there
okay thank you
how can i check if 2 objects intersect without using colliders stuff like on trigger enter
@fervent abyss You can check the distance between two object and if they are close enough trigger what you need
you can also use the bounds of their renderers to see if they overlap
how can i do that?
you get the bounds properties from both renderers and then you read https://docs.unity3d.com/ScriptReference/Bounds.html
hi, i have this code but i cant look to the sides, oonly up and down and the camera still dont attach to the player
may someone know the solution?
from what i see you only rotate by X axis here
you dont do anything Y axis related
😔
i followed a tutorial
and the guy could move all directions
i dont understand
😱Mejor explicación que FUNCIONA EXELENTE para TÚ PERSONAJE en PRIMERA PERSONA mas SCRIPT AQUI ABAJO :D Aquí te explicare lo que nadie mas explica a detalle y lo mejor de todo en menos de 10 min si te funciona déjame un comentario y un gran like que no cuesta nada :D
Regalo Script 🎁 Aquí 👇🏻
https://terabox.com/s/1J6jSdSexWWJSm3bUh6MEvA
🟣Twitch...
love how he copied the same brackys tutorial thumbnail and still made same mistake with Time.deltaTime
show whats currently happening
well first of all
it is rotating left / right
the camera is not child of Player
ofc its not gonna follow it
what
what dont you get?
u rotate the camera up and down transform
u rotate the player left and right.. player.transform
If you took your eyes out of your socket and just left them on a shelf, can you see where your body is going ?
when i move the mouse side to side only the player turn the head, but the camera dont do it
the player shuld be a child object of the player..
meaning it would follow the player if the player rotates
thats because the player is supposed to rotate the camera
i have to put the script in the player?
srry im not understanding jajajaja
yeah yeah yeah okey, i didnt put it there because before i tried but didnt work
because you had two cameras
now it works i think
that make sense
can someone tell me how to fix this camera glitch?
Hello, I have different types of projectiles in my game I kept getting missing reference errors for one kind, after endless searching for what was destroying them I realised it was another type of projectile (at least I'm 99% sure). However I thought that in my function I was telling it not to destroy that kind of projectile can anyone explain why it is anyway?
public void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.GetComponent<PlayerController>() != null)
{
Debug.Log("You Died");
GameController.i.SetGameOverState();
}
else if (col.gameObject.GetComponent<Bullet>() == null)
{
Destroy(col.gameObject);
Destroy(this.gameObject);
}
}
What is the specific error you are getting? What line?
hey guys, i'm having trouble with audio source, i have this little script that just play one sound, but I guess i have to attach an audiosource from here but there is no in the list
I think I've fixed it now, I am just curious why if what I think is the cause was that piece of code didnt stop it. But to answer your question it was this line:
Rigidbody2D rb = projectile.GetComponent<Rigidbody2D>();
And the error was MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
(The game is set up in such a way that the projectiles shouldnt be able to be destroyed before force is applied to them)
Why are you trying to edit the script defaults? You should set it on an instance in the scene
Where does projectile come from?
GameObject projectile = Instantiate(projectilePrefab, position, rotation);
Is it possible that you've accidentally set projectilePrefab to an object in the scene, rather than an actual prefab?
Nope it was definitely the prefab file
You probably have to add the audiosource. And apply an audio clip to it. Use the add component button in the inspector.
https://www.youtube.com/watch?v=f473C43s8nE&list=WL&index=10&ab_channel=Dave%2FGameDevelopment
watching this video, after limiting my speed so i dont infinitely accelerate, my character still continues to slide, but his doesnt, ideas why it seems like the ground still has no friction for me?
FIRST PERSON MOVEMENT in 10 MINUTES - Unity Tutorial
In this video I'm going to show you how to code full first person rigidbody movement. You can use this character controller as final movement for your game or build things like dashing, wallrunning or sliding on top of it.
If this tutorial has helped you in any way, I would really appreciate...
You could try to find out what's destroying the object by adding a log in OnDestroy:
https://docs.unity3d.com/ScriptReference/MonoBehaviour.OnDestroy.html
And see when it prints. I think you might even get the initial Destroy call in the stack trace
i didnt want to add audio clip i m trying to just generate a sound based on frequency and play a bit with its length @crystal chasm
But if you log in OnDestroy and also before the error, you can at least see the order
to create a sort of piano if you want
Ok. You will still need an audiosource for that.
It's a component
idk im just trying stuff
If you want to reference an AudioSource you need to reference it from an instance of this script. Not the file itself
okay
Quick question. Will StopCoroutine throw a null ref if the coroutine ends before the method is called. Not by string, but by reference overload
Not that I have ever seen.
With the code in my initial message
public void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.GetComponent<PlayerController>() != null)
{
Debug.Log("You Died");
GameController.i.SetGameOverState();
}
else if (col.gameObject.GetComponent<Bullet>() == null)
{
Destroy(col.gameObject);
Destroy(this.gameObject);
}
}
Is it impossible that what I suspected was the error is?
Because I havent encountered it since and im 99% its just destroying the projectile with the Bullet script on it anyway
Destroying your bullets all the time is not the correct way to go about it anyway. You should be object pooling.
It's possible, but "possible" doesn't become "is" without data
What on earth is object pooling?
If your projectile has a log in OnDestroy you can find out if it's getting destroyed somehow between instantiation and accessing the Rigidbody
tl;dr - instead of destroying and spawning an object, you have one object that you move around and deactivate and reactivate
It's where you reuse the same object a bunch of times instead of creating and destroying them.
Ahh ok I will add an OnDestroy just so I can be certain if i've caught the problem or not thankyou for your help
Ahhh I see for performance reasons right?
Yeah. Just google ObjectPooler Github... there are more than a few available
SimplePool is the one I have used for bullets.
Ahh ok awesome thanks for the tip ill be sure to check it out
How might I accomplish something like the following?
int x = 4;
string str = $"x: {x}";
x = 5;
Debug.Log(str); // I'd like this to print "x: 5"
I know the string object doesn't work this way, but I'd like to have a sort of dynamic string object that contains references to variables that change the string value when they are updated
I've written an overly complicated parsing function to sort of accomplish what I'm after, but I feel like there must be a simpler way.
how can I fix this I tried everything and I have no idea how to fix this? cant move camera
Debug.Log($"x: {x}");
!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.
how do I use this?
You follow the instructions
{
_inZone = true;
GameManager.instance.battleStarter = gameObject;
}``` i have 10 npc with this script, why does it trigger that on all of them?
Without having to reenter that. I have a string with like, 75 variables.
Probably because all of them are interacting with a trigger.
public void LogThings(int x){
Debug.Log($"x: {x}");
}
I'm looking for something flexible that can work with any number of variables in any given position in the string. It won't always be formatted the same way
So do you want something different every time or do you want something reuseable
because those are conflicting goals
int x = 4;
string str = "x: " + x;
x = 5;
Debug.Log(str);
That will log x: 4
...both?
All you've done to theirs is removed the string interpolation
ive figured out that the raycast im using isnt detecting that im grounded, anyone can help?
I somewhat suspect that what I want to accomplish is not possible.
But wanted to make sure there wasn't some dynamic string something or other that checks all the boxes
Its super ambiguous what you're actually trying to accomplish rn some context might really help
If you've got a lot of different things you want to use, at some point you're going to have to tell the code about those things. So you'll need to either use an interpolated string or make a function that returns a string
Show the inspector for your camera
Actually, the whole object with the camera on it
not just the one component but the transform and whatnot too
did you make sure to set ur layer on ur ground collider to whatIsGround
and assigned it here.. or if using some other mask.. making sure its applied to ur colliders?
string str = "x: ";
x = 5;
Debug.Log(str + x);
i believe so?
is the height high enough?
u can also debug the raycast hit to see if anything is blocking it
right now ive got a debug on the groundcheck, and the raycast seems to be hitting, but the console states, "grounded: false"
i dont know if my height is high enough, how do i check
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.
Include your logs
Sorry, long message
you can use https://docs.unity3d.com/ScriptReference/Gizmos.DrawRay.html to visualize ur raycast,
just feed in the position and (direction * length)
!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;
using System.Collections.Generic;
using UnityEngine;
public class XYZMovement : MonoBehaviour
{
[Header("Movement")]
public float moveSpeed;
public float groundDrag = 5f;
[Header("Ground Check")]
public float playerheight = 2f;
public LayerMask whatIsGround;
bool grounded;
public Transform orientation;
float horizontalInput;
float verticalInput;
Vector3 moveDirection;
Rigidbody rb;
// Start is called before the first frame update
void Start()
{
rb = GetComponent<Rigidbody>();
rb.freezeRotation = true;
}
private void Update()
{
SpeedControl();
MyInput();
grounded = Physics.Raycast(transform.position, Vector3.down, playerheight * 0.5f + 0.2f, whatIsGround);
if (grounded)
rb.drag = groundDrag;
else rb.drag = 0;
Debug.Log("Grounded: " + grounded);
}
private void FixedUpdate()
{
MovePlayer();
}
private void MyInput()
{
horizontalInput = Input.GetAxisRaw("Horizontal");
verticalInput = Input.GetAxisRaw("Vertical");
}
private void MovePlayer()
{
moveDirection = orientation.forward * verticalInput + orientation.right * horizontalInput;
rb.AddForce(moveDirection.normalized * moveSpeed * 10f, ForceMode.Force);
}
private void SpeedControl()
{
Vector3 flatVel = new Vector3(rb.velocity.x, 0f, rb.velocity.z);
if(flatVel.magnitude > moveSpeed)
{
Vector3 limitedVel = flatVel.normalized * moveSpeed;
rb.velocity = new Vector3(limitedVel.x, rb.velocity.y, limitedVel.z);
}
}
}
thats longer than i expected
💀 my bad
!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.
his raycast is just a boolean.. u can debug the value to see if it ever returns true..
the player height is cut in half.. so u can just increase that a bit higher just to test..
so what should i change in my code
just the player height?
its a process of debugging.. you test various things to rule out if thats the problem..
Is your camera being controlled by any of your animators? Try disabling the animators and see if the camera is still wigging out
how do i do that
so if player height is the issue.. u can raise that to some value high enough u know u'd get a hit..
and then if it doesn't u move to the next thing
Debug.log(grounded);
that would debug the value of the boolean named grounded
yeah that was legit the issue lmfao
i went into the inspector and changed the player height
no its not the animator
and now im not a peguin lol
So you are looking for a way to pass an arbitary number of arguments to a function, which logs these?
i wonder why the player height at 6 works and not anything lower
you are raycasting from half of the player height , plus some amount...
i mean i understand why the player height has to be high enough, so that the raycast is casting above the floor and not under it into the damn void, but why does it now work when its 6, and not my actual player height of 2
if ur player is 6 units tall.. then the code playerHeight * 0.5f would cut it in half.. soo ur raycast is then 3 units long.. and it starts at the point u chose.. soo probably transform.position which is the dead-center of the capsule..
In CamMovements, log Mouse_X and Mouse_Y after you get them
he includes a + 0.2f on his code. so u can use the exact player height.. and once its halved he makes it a tad bit longer.. so it will clear the mesh.. and touch the ground
In CamMovements, log Mouse_X and Mouse_Y after you get them
is there any scaling going on with ur player?
right, but why is it that my player height was the same as his but his was working and mine is
if the scales are not 1:1:1 then a 2 unit tall capsule really isn't 2 units
the code runs fine when i set the player height to 6, it doesnt change anything i dont think, but im just getting an understanding of it
idk, maybe minor differences
Clones are still spawning in the hirachie, after closing the game
private GameObject goBullet;
public float bulletSpeed = 10.0f;
public float intervall = 1f;
void Start()
{
InvokeRepeating(nameof(Shoot),0f,intervall);
}
private void OnValidate()
{
CancelInvoke(nameof(Shoot));
InvokeRepeating(nameof(Shoot), 0f, intervall);
}
private void Shoot()
{
var bullet = Instantiate(goBullet, transform.position, transform.rotation);
bullet.GetComponent<Rigidbody2D>().velocity = transform.up * bulletSpeed;
}```
Much slower then the 1 second, but it doesnt stop
Line's gotta be long enough to actually reach the floor
Well yea, you're running it in OnValidate
wdym log Mouse_X & Mouse_Y
I mean log them
if u use that drawray method i sent earlier u can draw a physical line in the editor to represent what ur ray is doing..
Debug Log should literally have been the first line of code you wrote in Unity
If you do not know what Debug Log is then you have missed a step. !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
i can check that out
its doing this
Does it always show 0,0 or does it change as you move the mouse
0s eh?
Okay, so it looks like your input manager gets you the mouse position, but your code is assuming it's mouse movement
I think? It's kind of hard to tell actually, the mouse doesn't seem to sit still for very long
Maybe show the input manager code as well
!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.
private void Awake()
{
Time.timeScale = 1;
foreach (VolumeSlider slider in vs)
{
slider.Init();
}
fade = FindObjectOfType<FadeToLoad>();
StartCoroutine(fade.FadeOut());
mainButtons.SetActive(true);
optionsScreen.SetActive(false);
}
why cant it find fade?
fade is there
@polar acorn
What makes you think this is the issue? What line is the error on?
it doesnt seem to be able to find the fade object
Okay, so it looks like it is a delta, so the code you've provided should be moving it normally. Make sure you don't have multiple things trying to move this camera or they'll fight each other
What makes you think that this is the problem though
what line is the error on
So theres nothing wrong with the input manager then?
Doesn't look like it. That seems to be the way to read mouse movement in the new input system
so is the problem with my other script?
The problem doesn't appear to be either of these scripts but something else. Disable your player control script and see if the camera still moves without it
yh its the player script
the error in the screenshot is irrelevant, im talking about the fadetoload thing. im assuming its because it hasnt found the volume slider, though
its the player script which also has the camera script how can I fix this?
The error in the screenshot is potentially very relevant
Just a quick clarification, OnEnable, just as anything on non-editor scripts just triggers during runtime, is that right?
Does the camera still move if you disable that script
Yes
Though so, thxs
im back, no more sliding, although it feels like my gravity is very low, how do i increase it? i think im just using the RB gravity as my base, im not sure tho
Do you have code that is setting Y velocity to 0? That'd overwrite your gravity from the previous frame
no the camera stops moving so the problem is the script
possibly? im following a video and trying to learn, so im not entirely sure if i do
@polar acorn take a look https://paste.ofcode.org/tQ45x2kQD6GL33tURaDc46
Add this log after you set xRotation, but before you do the clamp:
Debug.Log($"XRotation is {_xRotation}, Upper limit: {UpperLimit}, Lower limit: {BottomLimit}",this);
yeah probably youre right on second thought
should I put this in this line of code? _xRotation = Mathf.Clamp(_xRotation, UpperLimit, BottomLimit);
hey, i'm trying to program a board game, with a kinda open world, so i have spaces, but you can move in any direction to any of them. how can i get the distance in spaces between them? here a pic as visualization
I was overthinking it. I just need to have a custom getter for the string.
{
if (other.CompareTag("Player") && gameObject.CompareTag("EnemyWeapon")
|| other.CompareTag("Enemy") && gameObject.CompareTag("PlayerWeapon"))
{
test = true;
}
}``` why are both object true. only the left one should be tru
int x = 4;
string str
{
get { return "myInt: " + x; }
}
And just have a custom getter for each string, referencing whichever variable.
look at your bracketing or rather lack of it
well, I presume you are trying to isolate the 2 &&'s
https://paste.ofcode.org/dxR9bgDh84RPuT3BHbDJEy
this is my code for my players movement script
any idea as to why my gravity feels low?
ok so for testing purposes i removed one and both npcs are still true
needs to tune gravity and drag of the rigidbody
@polar acorn should it look like this?
if (
(other.CompareTag("Player") && gameObject.CompareTag("EnemyWeapon"))
||
(other.CompareTag("Enemy") && gameObject.CompareTag("PlayerWeapon"))
)
how
Time.deltaTime needs to be removed from both of those calculations
What does it print
thanks, but still both game objects become true, racking my brain as to why
we use keywords that are generally easily searchable.. and included in Unity
s documentation
How about you log the values and see what they are at time of collision
then you need to debug the tags. No need to think if you can read the data
im trying but theres a thousand things that i could do and idk what to do. im new to this stuff, i also dont really know how to implement code i find online into my own script as its not as simple as copy and paste
it didn't do anything
I mean it will definitely do something. Just maybe not solve whatever your current issue is
@wintry quarry praetorblue
Which I'm not aware of what that is
my problem...
Your look sensitivity is probably way too high for one
What's it set to?
should I lower it if so how low should I put it
You need to look at the inspector not the code
It should probably be somewhere between 0.5 and 5
1 would be a good starting point
@wintry quarry what should I put the upper limit and bottom limit?
That's up to you
Certainly upper should be higher than bottom though
Well except that you plugged them backwards in your code
So they're currently backwards
bro im getting stressed how can I fix this?? literally there is not one video about how to fix this I literaly cant look around and the camera is glitching
Every video tutorial is "how to fix it"
You'd have to also show how your input manager code works
I would guess that's the other part of the problem
The input manager code is likely not correct
not its correct I showed @polar acorn the input manager and he said its fine its the player script along with the camera code
I'm still waiting for you to post the results of the log I asked for
OMG I FIXED IT!! I just had to fix the upper and bottom limit lol
@polar acorn @wintry quarry Guys thank you for your assistance and help I've managed to fix some errors but here is the final product im soo happy 😭 ❤️
Any idea as to why im falling slower when im changing the velocity of horizontal movement
if (Input.GetKeyDown(KeyCode.W) == true)
{
myRigidBody.velocity = Vector2.up * jumpStrength;
}
if (Input.GetKey(KeyCode.D) == true)
{
myRigidBody.velocity = Vector2.right * walkStrength;
}
if (Input.GetKey(KeyCode.A) == true)
{
myRigidBody.velocity = Vector2.left * walkStrength;
}
You're resetting your Y velocity to 0 which is cancelling gravity
I need help. everything is working fine just one little thing. the camera is placed in the head and when im running the camera moves along with the head similar to when your running in real life how can I fix this
For several stats in a battle system, is it preferred to have several single int variables or one array of numbers for each stat?
Neither
Keep your previous Y velocity when you set velocity
I mean it really depends on your requirements
@polar acorn
But typically something more robust that supports augmentations and buffs and debuffs etc
Status effects, etc
@wintry quarry I need help. everything is working fine just one little thing. the camera is placed in the head and when im running the camera moves along with the head similar to when your running in real life how can I fix this
Don't put the camera in the head
Currently I have a class that contains data for a battle so I can store that and have methods to change stuff like status effects and buffs? So that’s where all the variables are
If there’s something better for that then let me know because that’s all I’ve seen / been able to come up with
i really dk how to do that 😭
But basically I have a class containing the ints for each stat
where shall I put it my game is a fps
You can get the current Y velocity with myRigidBody.velocity.y. You can create a new Vector2 by usnig new Vector2(x, y)
If ur trying to do third person I’d imagine putting the camera some distance behind the player
If u dont want first person
I want first person so where shall I put it?
On the head, as if you are running in real life, is first person
so then what is the problem
the camera moves along with the head is the problem
I want it to be still
But it's first person
ill show u
Like is it moving too fast or falling off or something ???
Because in first person it SHOULD move when you walk and turn your head
Put it in that spot just not a child of part of the armature like that. Just make it a child of the main player object
You see how the camera moves I dont want that @polar acorn @open veldt @wintry quarry
okay that makes more sense. I'm surprised you figured that out
I couldn't make heads or tails of that question
didn't fix it
im confused
wa
when i vector2.up
how come it resets the y velocity is what i dont understand
You're setting it directly what do you expect
Vector2.right * walkStrength is the same as new Vector2(walkStrength, 0)
See how the y value is 0
yeah
you're setting the y velocity to 0 and the x velocity to walkStrength
Meaning you're overwriting gravity
Like this kinda I can’t access discord on my pc rn so picture
Just don't zero out the y velocity. Keep that value
I'm saying rather than int use a whole class or struct that supports modifiers etc
Oooh good idea
im kinda stupid at this shit man
I love classes shoutout to classes
For a bunch of variables on the BattleInfo class though representing each stat, would it be fine to just have a single variable for each or should I put it in an array or list?
I’d use a dictionary but I’m hesitant because I have a save system with JSON and dictionaries don’t save
Or like they don’t convert to JSON
The most flexible thing is like a list and each stat object says what it is
Especially if not everyone or everything has all the same stats
But maybe they do
Dictionaries are fine as long as you know how to work with them and serialize them if needed
JSONUtility in Unity doesn't Serialize them by default that's all
They all have different ones this is basically a base class for things that need stats to battle
I’ll try a list maybe or I’ll try and see how dictionaries can be serialized since player stats need to help saveable
Dont wanna have my player grind for 3 hours n come back to level one lmaoo
so i have this (i took it from a post) ``` private void OnTriggerEnter(Collider collision)
{
string[] tagToFind = new string[] { "wall", "robot", "gameObjects", "walls", "doors" };
for (int i = 0; i < tagToFind.Length; i++)
{
var testedTag = tagToFind[i];
//compareTag() is more efficient than comparing a string
if (!collision.CompareTag(testedTag)) continue; //return early pattern, if not the good tag, stop there and check the others
Debug.Log($"hit {testedTag}"); //improve your debug informations
return; //if the tag is found, no need to continue looping
}
}
}``` the wall object looks like this. the controller that collides with it looks like this . ( this is my first time asking for help not sure what you all need help would be very much apperieicated)
I’m just trying to figure out how to structure this well, thanks!
forgot to mention the issue... it doesnt send anything in console
im very very very new to c# just started yesterday
OnTriggerEnter only works for trigger colliders
so put is trigger on?
If you want a trigger..
Maybe first understand what a trigger is
Otherwise you might want to look at OnCollisionEnter
ok
i forgot to apply the script onto the controller 😭
bruh . . .
Why do you run it in onvalidate?
Maybe you are not passing the parameter? What line?
the highlighted line in the image
Cause I want it to work on editor when the object becomes active
is the line that is causig the error
That’s not what validate is for
Put an ExecuteAlways attribute on the class instead https://docs.unity3d.com/ScriptReference/ExecuteAlways.html
That error looks like what happens when you have an AudioSource without an assigned clip
You have another copy of the script
I have ExecuteInEditMode, is that wrong?
Pretty sure I don't
That’s the legacy version of the same thing. Recommend is ExecuteAlways
Oh, now it doesn't return the error, but is not doing anything
Debug.Log to find out!
I just want the particle system to play on edit mode as soon as the game object is enable; though this would work but nah, it doesn't
well your code doesn't do what you probably want. its just wrong.
im using playoneshot with an assigned clip
use OnEnable/OnDisable and just call your Play/Stop there
PlayOneShot doesn't use the assigned clip
sorry i mean like a clip field thats assigned in the inspector
Doesn't work either
Right it doesn't use that. You pass it into the PlayOneShot call
can you get it to play without any of this scripting with the normal authoring controls?
Like with the particle gizmo you mean?
for example
Yeah, it does
In play mode too
I just want to sync it with an animation and I need to see both at the same time
i know this, but what i dont understand is that basically every value is set, and yet this error keeps happening. i dont know why
well, no idea then, i would have assumed this to be the way to play it, if that doesn't work something else is the issue or its not possible, idk
Can you show the stack trace for the error?
I want to create SOs where I store a callback function and would like to configure this through the inspector. Is there a way to assign functions to Action attributes in SOs through the inspector?
UnityEvent
You have code in SliderSelect.cs line 16
It's calling PlayOneShot with null
It's a listener to the on value changed for your volume slider
So they show but, but do I have to create static functions to link them to the SO?
(which is running when you set the slider value)
No they don't work with static functions.
On a ScriptableObject your options will be pretty limited. It'll have to be a function on a script on a prefab pretty sure
added a print to check.
public void ValueChanged()
{
print(hoverClip);
_audioSource.PlayOneShot(hoverClip);
}
oh wait
the audio source is null
but i dont understand
Is Collapse turned on in your console
Show the slider on value changed listener
is it hard to make an AI just go to the player position?
you mean here?
like in my game i just need an enemy to spawn in Know exactly where the player is then go to the player and if its in the range it should damage him and active an animation
which the dmg part is easy il slap a colider on that bad boy and if the player colides with it hit animation starts and it decreases the players hp
Click on that subscriber object (MusicSlider)
Where does it take you
idk how to do it tho
i was thinking maybe draw a raycast from the player to the ai and the ai should just follow it?
or maybe i can get the vector 3 of the player and tell it to go there but i dont think thatl work
it took me to a different object. i set it so master slider has the event listener for itself now, but the error still persists.
is there maybe smth like movetowards?
from what i can tell, its trying to call before it exists.
like transform.position = Vector3.movetowards(0, 1, 0)
So which object did it take you to? Can you show the inspector for that one?
ill record one sec
is there a good tutorial that teaches me the syntax of unity
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
why thank you
i've sorted it out 😄
different issue now, im getting the print log fine, but the audio mixer isnt actually reflecting the changes. this error only happens on startup, when the volume changes from player input it works as normal.
private void ChangeVolume(float sliderValue)
{
print("Changed Volume to" + sliderValue);
float volumeValue = Mathf.Pow(sliderValue, exponent);
audioMixer.SetFloat(channelName, Mathf.Log10(volumeValue) * 20);
PlayerPrefs.SetFloat(channelName, sliderValue);
if (sliderValue == 0)
{
audioMixer.SetFloat(channelName, -80f);
}
}
is it possible to say, place a prefab during runtime, but have it apply to the actual scene itself?
like realtime level editing
I hate the default 3D navigation and would like to make my own placement tools for certain things similar to GMod
in editor or a build? in editor it should be fairly easy to just use PrefabUtility to instantiate them
otherwise you'd need to create your own way to save a scene
im not sure what's possible really. I want to be able to run around the level in first person, point at somewhere on the floor, create an enemy there, make it look at me, then like have that be the new scene when I run it
guys people in youtube videos have this thing where it shows possible code you want to type, but it doesnt show it for me. how do i enable it?
!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
then yea you'll need a way to save these changes, writing to file in whatever format you want. If this is during playmode or expected to happen during a build, its really a lot more complicated than just in editor
is it possible to just like, add a script to the editor so I can do the things I said, just not "while the game is running?"
I mean maybe the file thing wouldn't be too hard
if it's just instructions for prefabs with preset values
like, could I have a scene with geometry and navmesh and all that, and then load a text file that says "this prefab at these coordinates with these variables?"
that might make it hard to visualize in the editor, but I could just give godmode and pause to the ingame or something
of course, you just need to code it to do that. and same for the question above about doing what you want in editor.
hm ok. wondering if that's maybe just what I should do, because I wast so much time trying to position stuff in the editor, very slow to edit placements and stuff
if its editor only, theres really no reason to be messing around with saving to your own file. You could create a tool that spawns certain objects for you depending where you look as you wanted but i truly doubt itll be saving that much time.
im not really sure what part you struggle with, like what are you placing thats difficult to edit?
it's just tedious
gotta find the prefab in a list, zoom into the right spot which is very annoying in Unity, click on it, drag it, hold buttons to make it snap, even though it doesn't snap properly, so I have to readjust it, then click on another tool to rotate it, etc.
would be a lot faster if I could just run there, right click on the ground, and the enemy is there facing me
or wall mounted object, etc.
🤷♂️ i doubt you'll get the behaviour you want from an editor script in this case, because you'd basically just be recreating the drag and drop that already exists.
yeah I'm thinking of making a file which keeps a list of prefabs to spawn when the level loads
then I can do something like, pause the game, place a turret in a spot I want to try with a few clicks, and restart the level
thatll honestly be way longer. especially cause you're kinda just skipping over the part where you're having trouble with placing it in editor already, whats the workaround gonna be? You can create your own script which lets you place with right click... but where will it place? Drag and drop already does it based on your cursor
it doesn't do it properly, I'll be able to set the exact spawn location with this instead of relying on "center" or "pivot", it will then also auto-snap the the normal I'm pointing at, and then depending on the object placed do other contextual stuff like looking at my location
or I could add a tool to link events like just point at a button, point at a door, etc.
i think maybe you just arent used to the unity editor 😅 this tool sounds nice on paper if it already exists. itll definitely be a good waste of time though especially if you go with the file route.
The only useful part really could just be creating a script which takes 2 objects, then rotates object A to look at B
especially loading your scene will just take longer
I mean I wouldn't use the file if it was possible to just directly add prefabs to a scene prefab from runtime but it doesn't sound like that's possible
well if you for sure wanna continue down this path, just know itll be a major pain in the ass. Especially during the development cycle where prefabs may change, be deleted, or new ones may be added. You'll need to reference it by some ID, and looking through this in a file to know which ones to delete are gonna be a headache. In which case you may think to further develop your editor tool, to allow you to delete objects. This is gonna be a lot of dev time sunk into a worse solution than just becoming familiar with the unity editor
the editor is not very quick to use
it's not specialized to my needs and the quicker I can edit a level the more likely I will be to expiriement
if there's no way to place an object in the scene in a permanent way from runtime, then I will have to use a file that loads them
Im watching a scripting tutorial video and theres this reference where it equals to "default", what this default statement do exactly?
Would there be any difference if i were to do
private GameObject attackArea;
```?
It sets the default value of the type. For most reference types it's null
No
It's just the tutorial person being fancy or silly
Or maybe they're just used to it.
Got it, thanks for the help
Maybe it's a convention they're used to
That's definitely silly, I hope it's not any popular convention
everything is default . . .
Or, maybe the code was decompiled 😱
that's my new thing. i use default instead of null . . .
Theres a major difference, for example default quaternion is not valid
structs and value types have a default. an int is just 0 . . .
Hello! I'm working on a project and need some advice. I'm making a score counter, but I'm not sure which approach is best. My first idea is to make an array similar to how I have the game objects spawning, and then using the array in an "if" statement to raise a score counter for each gameobject in the array that translates past a certain vector. If I do the first idea I'm planning on using one script on a gameobject that will be able to track the player score as well as the enemy score. My second idea was to make a script that I can attach to the gameobject prefabs that would change the counter as the translate past the vector that triggers the score change.
Also, not looking for help with the actual code just yet. I'm just trying to figure out which method would be better to use.
But their default is the same as not initializing them explicitly at all, is it not? So what's the point? I can't see any aside from readability, which is a preference thing.
Yes it does, but specifically a default quaternion is an invalid rotation. It gives 0,0,0,0
You probably need to be more clear about that; score counter is pretty generic; tell us what the game is about
Is it like soccer? Golf? A deathmatch? Scrabble?
3d top down shooter. Player scrolls side to side and fires projectiles and incoming gameobjects. If a game object makes it past thier score goes up. Player score goes up when hitting an incoming game object
You probably should just have a reference to the ScoreManager on each object prefab; when they collide with a bullet player score goes up; when they collider with a collider behind the player position, they score a point
You would need something to differenciate between those
hmm right now I have the prefabs getting destroyed when they pass a certain vector. It wouldn't be just as easy to trigger a score increase that way as well?
I mean, if it simpler to you; I would use colliders cause they are way easier to adjust than raw coordinates
Invoke("MyFunction", timeToInvoke)
Invoke(nameof(MyFunction), timeToInvoke)
```Whats the difference of using nameof() here?
Im watching a video where it says i shouldnt use invoke without nameof() but it doesnt really explain why
It helps you prevent human mistakes(typos) as well as not break if you rename the function(correctly).
it basically gets the name of the function as a string during compile time.
guys can someone show my how to setup ide
!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
Is there a way to use like... Random.InsideUnitSphere but give it an angle to sample for?
You could use Random.Range and Quaternion.Euler
Maybe randomize the x and y axes
And then multiply with Vector3.forward
Oh, ok, sure, thxs
Any Method to let Linear X max value become 3. I tried edit the key's value to 3 (like left's picture)but not working
How do you discard changes (not committed) in git?
I tried looking it up but they mention reverting commits and such
usually right click discard in github desktop :)
depends, if you are using a GUI for it you can typically select the file(s) you want to discard and right click to select discard changes (or whatever your GUIs equivalent is)
or you can use the stash command to discard but store them, or reset to completely remove them
I'm not using the gui yeah thats why I got confused because you right click and discard on gui but on command I was confused
hmm all right thanks
github desktop is trash anyway so good on you using the command line
fork is best gui
I have gitkraken just to check the stuff from time to time
oh yeah, another command you could use to discard changes is checkout
so I can stash and clear them all too?
aah good to know all right.
stash stores the record of the changes so you can apply them back in the future, like if you needed to stash changes before pulling or something. if you just want to completely remove the changes without storing them at all use one of the other options
okay I'll use reset or checkout then
also i believe version control discussion actually belongs in #1157336089242112090
stashing has created more problems than it has helped
rule of thumb, just fix the merge conflict over stashing if prompted
I have a dialogue manager which is what I use for all my characters dialogues. I'm trying to figure out a way that I can trigger certain events to happen at the end of a dialogue, For example, a character walks away. I thought about creating a method in the script, but the script is used for all characters, and I wouldn't want all characters to walk away after speaking. Does anyone have any idea what the best way to do this would be?
depends how far you wanna take this to be a "best" solution. Like the easiest thing i can think of would be a event. Simply just create another class, attach it to the same object, then invoke event after dialogue.
If it doesnt have the component, it doesnt do anything after.
The only part where this gets tedious is if this method will need logic passed in parameters, because your dialogue system might not have that information in the first place. In which case the component will need to get it by itself
Is it okay for me to move my scripts into different folders? I have loads and want to organise them, but i'm worried it'll affect something.
I'll do it within Unity too
I could use some help please
for some reason I'm getting an error, and I'm unsure why
spelling
Should be perfectly fine, as long as you do it via Unity
gonna turn all my strings to const, I can't with these strings lol
I moved my scripts but got this error
The only time this will affect anything is if you are using hardcoded file paths, or Resources to load something.
Just reopen the script, it's not an issue
It simply couldnt find it because it's not there anymore
Awesome, thanks!
So currently I have the following func made
IEnumerator Punch()
{
isPunching = true;
float initialAngle = rb.rotation;
float punchTargetAngle = initialAngle + punchAngle;
float punchReturnAngle = initialAngle;
float punchTime = 0f;
while (punchTime < punchDuration)
{
punchTime += Time.deltaTime;
float angle = Mathf.LerpAngle(initialAngle, punchTargetAngle, punchTime / punchDuration);
rb.rotation = angle;
yield return null;
}
RaycastHit2D hit = Physics2D.Raycast(transform.position, mousePos - (Vector2)transform.position, 1f, treeLayerMask);
Debug.Log("Punching...");
if (hit.collider != null)
{
Debug.Log("Hit: " + hit.collider.name);
if (hit.collider.CompareTag("Tree"))
{
Debug.Log("Hit Tree");
hit.collider.GetComponent<Interact>().OnPunch();
}
}
// Rotate back to the initial angle
punchTime = 0f;
while (punchTime < punchDuration)
{
punchTime += Time.deltaTime;
float angle = Mathf.LerpAngle(punchTargetAngle, punchReturnAngle, punchTime / punchDuration);
rb.rotation = angle;
yield return null;
}
isPunching = false;
}```
But what if there are 2 trees near and I am standing in the middle of it, or 2 persons. How would I do that?
I saw something like RaycastAll in the lib, can I use that?
!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.
How do I stop myself from making silly and extremely time consuming mistakes like this?
I was debugging this for hours ...
public async Task<string> EquipItem(string itemType, int itemId)
{
// Unequip item
if (character.EquippedItemList.ContainsKey(itemType))
{
// What it should have been
int equippedItem = character.EquippedItemList[itemType];
character = ActuallyUnequipItem(character, equippedItem, itemType);
// What I did
character = ActuallyUnequipItem(character, itemId, itemType);```
So basically I was unequipping the item I wanted to equip
go to youtube and type "unity jump tutorial"
swould this work
yield return new WaitForSeconds(respawnTime);
As it doesnt continue after the respawnTime (what is 5f)
sorry if this is a dumb question but, Im learning to use the Unity Input System (for 3D movement), how can I make it so when im holding down a button, the speed is kept constant? Since now, whenever I press a button, it gives the player a short burst of speed instead of constantly moving.
Track it in a bool. When the button press is performed, set the bool to true and then false when it is canceled.
I want to add a idle crouch animation and I was wondering do I have to put the same positions as normal idle?
Uhh well I assume I didn't do it right since my unity always crashes.
!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.
this is what happens when i press W and D or W and A instead of just walk in diagonal. Anyone knows what is the problem
To answer your question, yes raycastall will work for it. I would also implement an interface for punchable objects instead of comparing it with "tree" tag
Well I would assume your problem is code related please share the code and not in a video
!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.
first is playerController
second cameraLook
Guys i have a building problem idk why
open the log and see if it tells you why?
i fixed it
cannot use anything from UnityEditor namespace in a build
The camera is moving along with the animations how do I fix this?
fix?
@wintry quarry do you know how I can fix this?
okk
how
remove the using statement?
from all my sripts?
Only GameManager is throwing an error but unless you are writing Editor scripts I'm not sure why it would be in any script
So remove unity engine?
did I say that
bro im a complete noob idk what your saying
do you see the words UnityEditor there?
yes
so why are they there?
Dont ask me ask unity it was alr there
no it was not
and I am asking you, it is your code
and that has absolutely nothing to do with UnityEditor
This is the code inside the gamemanager
notice how lines 2 and 3 are greyed out? that means they are not being used, so remove them
so what other UnityEditor references do you have in your code?
Wdym
well, if you have any other scripts with a UnityEditor reference in them they are going to throw errors as well
OMG. Do any of them say UnityEditor. I must have typed this 20 times by now
no
Your controller script is doing this:
player.transform.LookAt(player.transform.position + movePlayer);
Get rid of that
The other problem is your mouse look is probably set way too high
So why are you using EditorApplication in those scripts?
the turn of the game on editor application?
I am trying to make a game inspired by Minecraft but better, how would I make a world terrain generator?
yes, that. That code cannot be in a build.
So you need to look at C# defines so you can add a conditional compilation directive
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives
or just comment out the line and be done
ok im just gonna remove the unityeditor . editapplication
comment it out, is the simpler way
no need i just did it anyways
its ment to be a prototype gam
a prototype game
so i can move on to making better games
since im still learning
there is buildrd
ama keep that on mind when i make another game
I spawn a object from a prefab. This should on Collision change a variable on another skript. How can I create a connection from the PointSystem to the prefab. It shows this:
I also tried to unpack the prefab an repack it, but it can't acces the other skript
You probably aren't wanting to modify the prefab but the instantiated instance. Cache the spawned instance and give it the necessary data.
var instance = Instantiate(prefab);
instance.pointSystem = pointSystem;```
`private void Shoot()
{
var bullet = Instantiate(goBullet, transform.position, transform.rotation);
bullet.GetComponent<Rigidbody2D>().velocity = transform.up * bulletSpeed;
}`
So you mean add it hear, or?
!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
Nvm, but thx I just watch a video about how to make bullets, there should be something on YT
where are you changing the goBullet though
What do you mean with changing
ohh nothing, Look fine.
Is AddForce for RBs calculated immediately, or after one frame? The question is when I do AddForce, does RB.velocity reflect this immediately?
It's tallied up and applied in the next physics update.
The velocity of the rigidbody will not immediately change.
It also might not change by the next frame.
(so if you apply force many times, the individual forces get summed up)
I have a question in relation to documentation and how to look up things in the documentation.
I recently had a problem where i tried to update my slider max value.
and i found this: https://docs.unity3d.com/ScriptReference/UIElements.Slider.html
in here i found properties would be "highvalue" that i should be editing. but it did not work. After a lot of troubleshooting and querying chatgpt i found out that this is for UIElements.Slider meanwhile i am using UnityEngine.UI.Slider which should have used maxvalue not highvalue as property
I then queried chatgpt how i can figure this out on my own instead of reverting to chatgpt every single time and it told me to look at the namespace and then look up "UnityEngine.UI.Slider" on the website, but doing so i still cant really find what i was looking for.
Ive gotten the stuff i needed to work via chatgpt but i would like to be able to look things up myself, verify i am looking at the right thing, and if not find the right thing. But even now that i know what im looking for i still cannot find it. Any tips ?
UnityEngine.UI documentation is found in https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/index.html
It used to be part of the core engine, but it was pulled out into a package a while ago.
oooh whatyt are the differences between these two pages ?
The script reference on docs.unity3d.com covers everything that is built into the editor
(you will find very old UI docs on there, from back when they were built in to the editor)
It is a pain point, since google often winds up giving you the old doc pages on the main site
i see, so i gave your link a go there and i foudn thhis: https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/script-Slider.html?q=slider
so this wouldve been what i was actually looking for isthat right ?
Right: that's the manual for the slider. You will also want to see the scripting API page.
oh my even looking up things are difficult xD
I'm not a huge fan of the layout for package documentation
it doesn't have a single list of all of the members
it looks like this in the old docs
yeah, i am not so much of a fan either because its extremely difficvult for newbs like me to find things and know if it is the right thing im looking for, but i really appreciate you clearing this up for me
oooof
clicking on one will take you to that spot on the page though
Unity UI is the one thing that's really annoying to look up like that
yeah, haha thanks ima save these links for the future i think this is gonna save me a lot of trouble atleast
thanks man !
no prob
how can i fix this issue?
i have a code that makes the model look at the bean (player)
and it keeps looking above the player and once it gets super close it just looks up
i was thinking about making a empty gameobject and tell the code to look at that
📃 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.
public float ChildSpeed = 4;
// Update is called once per frame
void Update()
{
transform.position = Vector3.MoveTowards(this.transform.position, PlayerBody.position, ChildSpeed * Time.deltaTime);
transform.LookAt(PlayerBody);
}```
so, the problem is that LookAt is rotating the transform so that it's forward vector (the blue arrow when you select it) points straight at the target
its a very tiny code since its also simple
An empty object attached to the base of the player would fix this on flat ground.
But you'd have problems if the player was above or below the model
ok great
it'd do the same thing: tilt forwards and backwards
it didnt btw
What you can do instead is something like this:
Vector3 target = PlayerBody.position;
target.y = transform.position.y;
transform.LookAt(target);
var target= PlayerBody.position
target.y = transform.position.y
LookAt(target)
jinx 😉
oh nvm 🦥
far and close
oh ok
This ensures that the enemy always looks at a position on its own Y level
should i switch the target to the name of the transform? like i want it to look at the Transform of PlayerBody should i switch target to player body?
oh no
the target is the playerbody
target is literally a copy of playerbody minus the Y
Right.
yep i jsut read the code
I just used a different name there
(the variable name doesn't matter at all!)
you could call it florp and it'd still work
alr now it just jumps i think if i freeze the Y movement of it it should fix it
oh no nvm
the collider is aliltle in the ground
so it gives the ilusion of jumping
is there to make it so it also doesnt want to go to the y level of the player
i think its cause its also going to the y level
so if i somehow tell it to only go to the Z and X then it shouldnt fly should it?
Right, and you'd do that in the same way
although, maybe not: this would prevent the model from going up or down to reach the player
Ideally, the player's root should be positioned at the player's feet
with the capsule body and camera parented to that root object
how do I combine meshes on unity?
it wouldnt tho would it?
If you did this:
Vector3 destination = PlayerBody.position;
destination.y = transform.position.y;
the model would never be able to move up or down
you generally just stick them together in a prefab
e.g.
note that this isn't a code problem
I still dont understand, sorry, Im a very beginner in unity...
I saw a tutorial
that used code
to fix this
okay, and what tutorial is this?
may I send a link here?
that's what i'm asking for (:
I just wanted ads in my game.
you have a giant pile of syntax errors
your code editor should be highlighting all of them for you
I said to post your !code
make sure that IDE is indeed configured
!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.
This is a bit advanced, but sure, let's talk about how to combine meshes. It's pretty straightforward once you know how!
Multimaterials: https://youtu.be/6APzUgckV7U
okay, that is indeed combining multiple meshes together via code
What are you trying to accomplish here, though?
https://hatebin.com/lukapcwurf heres the code
not "combine meshes"; that's the attempted solution to your problem
less space taken
storage space?
completely irrelevant
you have the same amount of mesh data no matter how you mash them together
(and Unity will already do this for you with static batching!)
Focus on making a game, not on trying to micro-optimize it
What! thats Java not C#
I am making a vrc avatar
not a game
combining meshes will do nothing to your triangle count
I was thinking about that its a different language...
also, combining meshes with blendshape data sounds miserable
Where do i find it in C sharp
If you want to merge meshes together, do it in Blender.
That will be much simpler than trying to script it in Unity.
ok!
no idea, where did you find that?
how can I optmize my avatar so it ocupies 1/9th of the space?
perhaps ask about this on !vrchat
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
ok
are you actually concerned about file size, though?
perhaps you're talking about vertex count, or material count, or something else?
file size is certainly nice to keep low, but it's not what you're usually trying to cut down
I'm not seeing any java on this page
And you did the Android developer bit instead of the Unity developer section
OMG, im so stupid. Thanks!
What's some useful books you lot would recommend for someone who's only got a bit of experience with Unity and C#? I feel books force me to learn compared to video tutorials . Also I've a cs degree but can't code to save my life so want to start over learning from scratch 🙃
lol, I wont even ask how you managed to get a cs degree and not be able to code
Why does my ads not show?
Ok, come on!. How the hell would I know that
It wanted this right?
Uni doesn't teach you to code that's why haha. I lost interest with CS as most topics bored the crap out of me too. Originally was gonna do game dev degree. Mistakes were made
lol schools lower expectations
I knew Uni's had dumbed down a lot since my day but that much is bloody frightening
they lower standards, more students pass, school looks good. IQ of the country slips another few points
Aye mate you'd be suprised haha. Now with GPT very few students learn to code so it's gonna become worse in the next few years
There's a reason why I work as an IT tech and not a software engineer haha
https://hatebin.com/gaapubrjeb my raycast wont work at all
it doesnt even debug anything to the console
Did it not occur to you to Debug what it does hit? That may give you a clue
hmm ill try that
nothing happened
Also if it hits nothing that code will throw a Null Ref exception
it didnt throw anything
is it even running?
yes 😭
prove it
i ran Debug.Log(raycastHit.collider.name);