#💻┃code-beginner
1 messages · Page 147 of 1
You want:
float xInput = Input.GetAxis("Mouse X") * mouseSensitivity;
rb.rotation *= Quaternion.Euler(0, xInput, 0);``` @twin bolt
wot
Ok
the value is stuck at -0.0200000 whenever the game starts, idk what's causing it tho
what value
the Y value
Of what
Y value of my player when the game starts, tho its presetted to 0 by default
Oh yeah sorry
The Y value of my player's position is going to 0.02000 when the game starts
well.. you have gravity: characterDirection += Vector3.down * characterGravity * Time.deltaTime ;
it's falling
i removed it and tried, however it seems that being on the box collider ground makes it like that
I use different types of main controllers with different scripts in my games so I'm worried that it'll bring in my main controller from the base scene into the game, instead of simply leaving it there in it's original position
Because the tutorial said that it brings the main controller into the next scene, and I don't want that to happen
Just added lines 25, 26, and the start function, but I'm getting this error, anyone know how to resolve it?
you can't have yield return in a method that isn't a coroutine (technically called an "iterator" in C#)
- https://screenshot.help/
- You can't put a yield instruction in a non-coroutine method
also where on earth did you come up with yield return new((float)0.2);
I'm sure it's a code issue, but can i ask why i dont see object sprite? I have object called Cursor (transform.position = Camera.main.ScreenToWorldPoint(Input.mousePosition). Also sorry for my English
It's position is working fine but sprite is gone
Camera.main.ScreenToWorldPoint(Input.mousePosition) is going to give you a position at the same z location as the camera
which will not be visible to the camera
where problem? It's not in a Code
so i need to keep z == 0?
I guess only objects with Z == 0 will be visible
recommended:
Vector2 worldMousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = worldMousePos;```
only objects in front of the camera
I have an enemy with a 2d rigidbody and boxcollider which I am moving in the Update function using rigidBody.velocity = movement; Movement is decided in a coroutine with this function
private IEnumerator ChooseDirection()
{
chooseDirection = true;
yield return new WaitForSeconds(4f);
movement = new Vector2(Random.Range(-1f, 1f), Random.Range(-1f, 1f));
chooseDirection = false;
}
My wall collision does this to invert its movement and go away from the wall(I tried multiple things but couldn't find the right idea)
rigidBody.velocity = new Vector2(rigidBody.velocity.x * -1, rigidBody.velocity.y * -1);
The problem I have is that when it collides with a wall (also a boxcollider) it doesn't invert the velocity it had. I'm also facing the issue that the front of the enemy is not always facing the directions it's going which I assume can be fixed by changing its rotation instead of the velocity I do right now. But how would I invert its rotation when it hits a wall then?
thank you
❤️
What are you trying to do exactly?
do you want to invert or reflect?
inverting would just be -
but in OnCollisionEnter, the velocity has already changed from the collision
inverting, if its moving NW it should go SE
then rb.velocity = -movement; no?
can i ask what's difference between this and direct assignment?
Please can anyone help me? Theres only input for wasd but this appears out of nowhere
Using a Vector2 drops the z
ty
so when we convert back to a Vector3 z is zero
now it works
thats what i tried as well but it sticks to the wall and im indeed using OnCollisionEnter2D what should I use instead? OnTriggerEnter?
check if you have digital normalized active maybe?
i don't see why that would make it stick to the wall unless you're also changing mvoement at that time. You should show all your code.
@pliant raptor
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Wall")) {
//rigidBody.velocity = new Vector2(rigidBody.velocity.x * -1, rigidBody.velocity.y * -1);
rigidBody.velocity -= movement;
}
}
This is the entire collision function in my enemy script
why are you doing -= movement
Shouldn't it be this? #💻┃code-beginner message
yep, misread that but it still sticks to the wall
sorry i have no idea
hallo
Ok, new problem. I'm trying to make code that updates the sprite of a gameObject every time my timer reaches a certain value. The problem is, the sprite updates every frame rather than once.
swingTimer += Time.deltaTime;
if (swingTimer >= .50)
{
swingTimer = 0;
}
else if (swingTimer >= .30)
{
currentFrame++;
}
else if (swingTimer >= .20)
{
currentFrame++;
}
else if (swingTimer > .10)
{
currentFrame++;
}
spriterenderer.sprite = spriteArray[currentFrame]
I've tried using Mathf.approximately(), but the problem with that is, given a lower framerate, it is possible that the timer never reaches said approximate value. How do I code this so that the sprite only updates once per comparison, but still insures that the sprite won't be skipped?
This seems like a very very complicated way of remaking the animation system
cause if I keep the velocity to the right this is what happens movement = new Vector2(1, 0);
https://gyazo.com/09d72313cbda480102ee77e39b9923b8
float[] times = new float[] {0.1f, 0.2f, 0.3f, 0.5f};
int spriteIndex = 0;
for (int i = 0; i < times; i++) {
if (swingTimer > times[i]) {
spriteIndex = i;
}
else {
break;
}
}
spriterenderer.sprite = spriteArray[spriteIndex];
There's an animation system? 💀 I was not aware.
show the rest of your code please
you have shown very little code
An Animator Controller is a Unity asset that controls the logic of an animated GameObject. Within the Animator Controller there are States and Sub-State Machines that are linked together via Transitions. States are the representation of animation clips in the Animator. Transitions direct the flow of an animation from one State to another. In thi...
this would've been nice to know about sooner lmao. thank you.
also when trying to implement this code, it gives the error Cannot implicitly convert type 'float[]' to 'float'
I made a typo
fixed it
oh ok thx
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.
you're doing rigidBody.velocity = movement; in Update
so really you'd need to also do movement *= -1;
i.e.
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag("Wall")) {
//rigidBody.velocity = new Vector2(rigidBody.velocity.x * -1, rigidBody.velocity.y * -1);
movement *= -1;
rigidBody.velocity = movement;
}
}```
Is there any better way to do this?
RaycastHit2D hitLeft = Physics2D.BoxCast(PlayerDB.coll.bounds.center, PlayerDB.coll.bounds.size, 0f, Vector2.left, .1f, PlayerDB.spikesLayer);
RaycastHit2D hitRight = Physics2D.BoxCast(PlayerDB.coll.bounds.center, PlayerDB.coll.bounds.size, 0f, Vector2.right, .1f, PlayerDB.spikesLayer);
RaycastHit2D hitUp = Physics2D.BoxCast(PlayerDB.coll.bounds.center, PlayerDB.coll.bounds.size, 0f, Vector2.up, .1f, PlayerDB.spikesLayer);
RaycastHit2D hitDown = Physics2D.BoxCast(PlayerDB.coll.bounds.center, PlayerDB.coll.bounds.size, 0f, Vector2.down, .1f, PlayerDB.spikesLayer);
if (hitLeft.collider != null || hitRight.collider != null || hitUp.collider != null || hitDown.collider != null)
{
OnSpikesInteraction?.Invoke();
}
I'm trying to move objects using cursor, but something is wrong and joint is weak and working wrong (i'm working wrong i know)
here is the code:
public class Cursor : MonoBehaviour
{
void Update()
{
Vector2 mousePosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);
transform.position = mousePosition;
if (Input.GetMouseButtonDown(0))
{
this.Activate();
}
else if (Input.GetMouseButtonUp(0))
{
this.Disactivate();
}
}
public void Activate()
{
RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), transform.forward);
if (hit.collider && hit.collider.gameObject.GetComponent<Rigidbody2D>())
{
this.GetComponent<HingeJoint2D>().enabled = true;
this.GetComponent<HingeJoint2D>().connectedBody = hit.collider.gameObject.GetComponent<RigidBody2D>();
}
}
public void Disactivate()
{
this.GetComponent<HingeJoint2D>().connectedBody = null;
this.GetComponent<HingeJoint2D>().enabled = false;
}
}
ah ofcourse, that did it. Thanks a lot
What exactly does this code do? What are you trying to achieve with this?
I understand the code, but I’m not sure why there’s 4 box colliders instead of one big one
That's the point, I don't know how to make a big boxcast.
Hello! I am following a tutorial online to make a RPG. When i make my player attack it does not go back to his idle form again. In the tutorial he does. Anyone that could help me real quick?
Show what you've tried
// Update is called once per frame
private void FixedUpdate() {
if (canMove) {
// If movement input is not 0, Try to move
if(movementInput != Vector2.zero){
bool success = TryMove(movementInput);
if(!success) {
success = TryMove(new Vector2(movementInput.x, 0));
}
if(!success) {
success = TryMove(new Vector2(0, movementInput.y));
}
animator.SetBool("isMoving", success);
} else {
animator.SetBool("isMoving", false);
}
// Set direction of sprite to mov dir
if (movementInput.x < 0) {
spriteRenderer.flipX = true;
} else if (movementInput.x > 0) {
spriteRenderer.flipX = false;
}
}
}
The halfExtents parameter sets the size
canMove = false;
}
public void UnlockMovement () {
canMove = true;
}
And then on the animation i added a event that triggers both
at the start it triggers Lockmovement at then end it triggers UnlockMovement
Also link the tutorial you're following
Guide on many of the first steps building up a top down 2d pixel art RPG from scratch in Unity 2022 version. The goal of this crash course is to cover as many relevant beginners topics as we can but linked together in actually building out some prototype mechanics for a potential game.
For the video, I'm using this mystic woods pack for this tu...
1:03:23
well maybe 3 mins earlyer but around there
Place a log in unlock and lock movement to see if they're occurring - order might be important as well.
a log?
Print/Debug.Log
Show the console logs from the Unity Editor console window
So lock is spamming
So unlock is not occurring. Figure out why.
Thats the whole problem it should be doing that
Well, it isn't. Figure out why. You ought to have a grasp of what makes it occur
Check the conditions and see why it doesn't occur
So my game for some reason
After pressing on my retry button
On the next retry
the retry button gets triggered by Spacebar key
lol
I don't know if its because i was enabling and disabling scripts or not
Could it be that after clicking my UI button once, it becomes highlighted by the game and that's why I can press Spacebar to trigger it? Because after focusing on another window and then going back to the game, the problem disappears
Yes, the button is in a focused state. Most apps do that, even Windows. Clicking on the task bar, hitting Tab to move the focus to one of the pinned apps, then pressing Space or Enter opens it
Is there a way to not give a button focus upon first clicking it?
becuz it also triggers another action in my script unintendedly lol
Is there a way to prevent focus upon clicking a button?
Yes from the event system, using EventSystem.current.SetSelectedGameObject(null)
You'd call that inside the method that executes when the button is clicked
Ah thank you very much!
just to make sure I'm not crazy these draw the same ray right???
because the drawn rays arent intersecting with something visually but theyre still reading as a hit and I need to know if my hitboxes, post hit code, or rays are wrong
what is this? 💀
exactly what it says
idk what i have to do
google it , should be pretty common result
okey
you won't see debug rays hit anything, you'd have to code that inside the If statement with DrawLine (origin, rayhit.point)
Hi, I have a projectile prefab with stats like bulletSpeed. During runtime, player can pick up powerups that can increase bulletSpeed but I don't want the change on the prefab to be kept after runtime. What can I do about it?
use another script that handles the boosted stats
Okay thanks
idk exactly how to fix your problem, but this script is too tightly coupled to your other code.
a script that controls movement should not have any references to player health, at all
also, you have a ton of magic numbers
like flatVel.magnitude > 400f
imo, for any movement script, you want to keep the update and fixed update loops as clean as possible
they will become absolutely massive
and make it a lot harder to fix anything
the majority of your fixed update loop contains information about collision for damage. none of that belongs here
you’ll find it’s a lot easier to find and fix problems once you separate all of this out
400 is also insanely fast, is your enemy a bullet?
then your units are wrong
m/s = m/s * const. implies const is dimensionless. so if const depends on mass, you fucked up
you're using AddForce wrongly
oh wait, no, I misread. That is fine.
I thought you were using it to apply force once
(like when you shoot a bullet)
This is applying a constant force to the projectile
If the projectile is heavy, then you'll need more newtons of force to accelerate it
either way, he is taking a vector, making it magnitude 400, and assigning the x/z components to velocity
I don't see ray pass through hitbox?
yea they pass through
they don't collide I mean (talking about Debug ones)
ik I'm saying they dont pass through
void FixedUpdate()
{
timer += Time.deltaTime;
Move();
~~float interactRange = 0.5f;
Collider[] colliderArray = Physics.OverlapSphere(transform.position, interactRange);
foreach (Collider collider in colliderArray) {
if (collider.gameObject.CompareTag("Player")){
Jump();
}
}~~
~~if(health == 0){
Destroy(gameObject);
}~~
}
void Move() {
Vector3 direction = (player.position - transform.position).normalized;
m_Rigidbody.AddForce(Vector3.forward * -2f, ForceMode.Impulse);
Vector3 flatVel = new Vector3(m_Rigidbody.velocity.x, 0f, m_Rigidbody.velocity.z);
// limit velocity if needed
if(flatVel.magnitude > 2f)
{
Vector3 limitedVel = flatVel.normalized * 2f;
m_Rigidbody.velocity = new Vector3(limitedVel.x, m_Rigidbody.velocity.y, limitedVel.z);
}
}
~~void Jump() {
if(timer > 0.5f){
playermovement.health = playermovement.health - 10;
timer = 0f;
}~~
quick easy fix
your code is now better. Not totally fixed, but better because i got rid of a bunch of crap that does not belong in this script
I'm just getting a second source to make sure these rays are the same
idk what you mean by that
@queen adder
are the rays in the debug drawray and the raycast the same origin and length?
\and direction
etc
public static World ReadWorldJSON(string name)
{
var jsonString = Resources.Load<TextAsset>("Worlds/" + name);
return JsonUtility.FromJson<World>(jsonString.text);
}
public static void WriteWorldJSON(World world)
{
string jsonString = JsonUtility.ToJson(world);
string filePath = WorldDirectory + world.WorldName + ".json";
File.WriteAllText(filePath, jsonString);
}
how do i write to the file using Resources api?
when I say “it has no business being there”, I don’t mean dance around it. I mean delete it, and put it in a totallt different class
i use a JsonFile utility from the youtuber velvary to handle that stuff
FileHandler, i think it was called
Try it and see
Resources is not used to write data.
It is strictly used to load Unity objects
i think so
Resources only loads files from a Resources folder. It doesn't load arbitrary files from disk at runtime
i don’t remember if she has a follow up that was fixed or something
imagine the difference between loading a Mesh asset and reading an FBX
You should save to Application.persistentDataPath instead
indeed: that's where you read and write files
I store my settings.json file there, for example
how would I try it? is it possible to just draw a raycast or?
I'm confused on what you're asking, aren't you already using Debug.DrawRay ? whats wrong with it
this should just turn any children of the gameobject towards idealTargetLocation right?
public static string WorldDirectory = Application.persistentDataPath
public static World ReadWorldJSON(string name)
{
string jsonString = File.ReadAllText(WorldDirectory + name + ".json");
return JsonUtility.FromJson<World>(jsonString);
}
public static void WriteWorldJSON(World world)
{
string jsonString = JsonUtility.ToJson(world);
string filePath = WorldDirectory + world.WorldName + ".json";
File.WriteAllText(filePath, jsonString);
}
something like this?
iirc you cannot assign it like that, has to be inside method
and you should be using Path.Combine
or well, it should m.transform.position, not transform.position
however, it appears that it
doesn't work
whats not working also you can just loop through transform
since thats a collection
(Transform t in transform)
its turning the parent gameobject instead of the child
it seems to work 🤷♂️ye ima use path.combine
oh weird.. maybe cause i was doing string interpolation
oh well
might want a subfolder though
I can't really tell whats happening, which ones am i looking at at? small ones?
are the pivots correct?
ok yeah sorry- didn't explain
the entire gameobject, even the parent, are turning towards the ideal target location
and i have no idea why-
and I assume that its nothing to do with the code I posted
probably because one of the items in the array is the parent
Neat. Switch does not have to be Int. it works with Strings too
switch is just a fancy if else if
indeed. i think the ability to use String is somewhat new though, in Unity
oh that explains it- how can I only make it have children?
Just make an array of transform in the inspector and drag them inside
[SerializeField] private Transform[] childTurrets
private void SufferDamage()
{
StartCoroutine(FlashSprite());
}
private IEnumerator FlashSprite()
{
_damageSpriteRenderer.color = Color.white;
yield return new WaitForSeconds(.1f);
_damageSpriteRenderer.color = new Color(0f, 0f, 0, 0f);
}
Someone told me that using WaitForSeconds is bad. Would this be okay for a quick damage indicator?
I've been having issues with using 'LoadSceneAsync' and 'UnloadSceneAsync' for switching scenes
Either the code doesn't let me unload the scene or it completely resetsthe base scene, which I don't want
I'm not using Timescale for the end of the games either
So I'm not sure what's wrong
Show your code.
Which one? Because I have that function in a few other scripts relating to each game's respective controllers
All of them?
📃 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 SufferDamage()
{
StartCoroutine(FlashSprite());
StartCoroutine(FreezeGame());
}
private IEnumerator FreezeGame()
{
var priorTimeScale = Time.timeScale;
Time.timeScale = 0f;
yield return new WaitForSeconds(0.05f);
Time.timeScale = priorTimeScale;
}
Damnit, another issue. It seems WaitForSeconds is affected by time scale. How would I freeze the game and unfreeze it after a bit?
use WaitForSecondsRealtime
Use WaitForSecondsRealtime
zoop
Ok
Double kill
This one is for the base scene, where I'm going to the playground items that I use to warp into the games themselves
(Had to use screenshots because I reached the character limit)
And this one is for one of the games (all three work very similarly)
I had to take the inputs for getkeycode out of OnTriggerEnter otherwise it wouldn't work
transform.left does not exist?
please share large amounts of code via one of the paste sites from that bot message #💻┃code-beginner message
Ah, thank you.
IDK how they're supposed to work
I put in the code and copy it but Discord still says I reached a character limit
sorry, I'm new to this stuff
You're trying to call SetActiveScene too early, methinks
Even LoadScene doesn't actually load a scene until the end of the frame
I want to make a 3d dungeon generator, what's the best way to do it?
so calling SetActiveScene immediately after LoadSceneAsync sounds way too early
When abouts should it be called?
Should it be done in a code linked to the new scene? When it's loaded in?
You could listen to the completed event on the AsyncOperation that LoadSceneAsync returns
I guess you could also just do that in Awake in something in the new scene
Although I'm not confident about the exact order of things there
Another thing is I tried to use the UnloadSceneAsync for when I wanted to exit the Jungle Game but it didn't work
It said something along the lines of "unloading the last loaded scene is not supported"
that means you only have one scene loaded
i have ran into a prbolem can anybody tell me how to fix this?
oh yeah, there's the thing I completely glossed over
just because you load a scene asynchronously doesn't mean you're loading it additively
That just means that you're allowing the game to keep running as Unity fetches stuff from disk
the error message tells you how to fix it
did you follow the instructions in the popup?
yes i don't understand the instructuions
You clearly have compile errors @delicate slate
listen to the error message - you have to fix them first
ok
And don't let me ever see you using Unity with your Console window hidden again!
whats that?
oh
boi
Is there a way I can load it additively?
Impossible to use Unity without the Console window
ya i js looked at it and um
sure, just pass LoadSceneMode.Additive as the second argument
the default is LoadSceneMode.Single
After LoadSceneAsync?
is it hard to fix this many bugs?
Those errors should tell you what file to look in, find the stuff underlined in red and fix them
they're simple
its mostly syntax/formatting issue
No. Pass it as the second argument to LoadSceneAsync.
whats that
when you don't know something, google is your best friend
a syntax error is when your code has an invalid structure
int x x x xjkdf = 3;
this is invalid syntax.
^ also you're missing ; and that makes more errors else where
i dont have friends
me?
cool. then google should be your first
since online search with the keywords i used was unsuccessful, how do i do
if (value = float range )?
i want the if to trigger if the value is inside a range of 2 float values
if(value > min && value < maxValue) ?
that makes perfect sense
So i'm trying to make a draggable inventory system and am implementing the IPointer interfaces right now. Would it make more sense to put a script on each of the "slots" in my inventory to control the drag? or to put the script on the container of all the slots in the inventory
what do the slots do besides get dragged?
whatever is easier for you to get reference to the slot to move it or if you need to do additional logic
swap items around, combine stacks, etc
imagine the inventory in minecraft for example
Whatever makes more sense to you imo
so it doesn't particularly matter?
I have worked on projects that had both it makes no functional difference
okay thanks
Made the scene I wanted to load additive and then this happened. Is there something else I'm missing?
this is a code channel
In the code I meant
your issues are clearly related to lighting
No, I meant that the scene just merged with the previous scene instead of switching
752 errors 😮
that's literally what additively loading a scene is for
I was told earlier that it would fix my issue of loading from one scene to another
i don't know what issue you were having before. but if you don't want both scenes active then you need to unload the other scene
and what is that?
im currently beyond confused. my enemy starts by facing right and having a Y rotation of 0. and every time he turns it adds 180f to his rotY. meaning, in theory it should alternate between 0 and 180.
then i have the section where its
if(enemy.rotation.y > min value && enemy.rotation < max value)
but the things inside this if stay triggered even when the conditions arent met anymore and it should switch to else.
Am i doing something wrong?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I wanted the previous scene to keep my position from when I reload into it, after I finished my minigame I load into
i can just see you're using quaternions
which is wrong for regular angles
transform.rotation is not expressed in degrees because it is a quaternion
then instead of loading additively you should store that information somewhere that is accessible even when switching scenes and when you load back into the other scene get that info and apply it to the player
@shell herald what you want is .eulerAngles or localEulerAngles if you need local
i js changed my script and it still isnt working the file name and monobehavior name match
configure your !IDE so it underlines your compile errors in red
wrong picture mb
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
you have errors
Make sure that there are no compile errors and that the file name and class name match.
so i just have to change the enemy.rotation.y to enemy.eulerAngles.y in both the Rotate and the if right?
the class name does match
Make sure that there are no compile errors and that the file name and class name match.
yeah that should give you the ones you see in the inspector (those are euler angles)
always use Debug.Log and double check
how i would i fix those i dont understand the instructions for the errors
Look at the lines underlined in red in your IDE and then fix them
For example
this fuckin thing
what is that
i dunno
then why did you put it there
wtff goin on there
it's not underlined in red is what it is. get your !IDE configured if you want to get help here 👇
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
i js copied it from a tut
Please show me the tutorial that said to put that there
100% it was just code in the description or comment on a youtube video lmao
In this Unity tutorial, I teach you guys how to make a basic third person character controller in Unity using the C# programming language. This character controller allows you to jog (forward and back), sprint, and rotate around for basic player movement. I also show a few easy camera methods as well.
#Unity #Unity3D
For more Unity tutorials o...
can anyone please help me? in my script there is if (Input.GetKeyDown(KeyCode.E)) but it doesnt work nothing works after the if
ya im probably going to check
oh
u were right
it was js extra stuff i copid
"I did it exactly like the tutorial so why does theirs work and mine doesn't" counter:
Number of times it wasn't exactly like the tutorial: 141
Number of times it was exactly like the tutorial: 5
Number of times the code literally did not exist: 1
2022-07-19 to 2024-1-16
now do this: #💻┃code-beginner message
What calls PianoStartedPlaying
which one do i click?
PianoTrigger script
I am pretty sure it is configured, it's just using the theme that tints errors red instead of underlining them
Okay, and did you start pressing E the exact frame you entered the collider?
but everything has a red tint to it in their screenshots. why the fuck would anyone want that
no i waited a second
Everything has a red tint because the whole fucking thing is an error because the literal first line is nonsense
it def doesn't look configured
You are checking if you pressed E this frame during the first frame of contact. Unless both things happen literally simultaneously, nothing will happen
ohhh and how should i do it so it checks all the time im in the trigger?
I have no idea what a configured VSCode is supposed to look like, especially if it has themes
Check for it in OnTriggerStay
maybe the still have old C# plugin with the mono but highly doubt xD
You can press alt + print screen to just get the window you want to screen cap
@delicate slate
Stuff like the references missing I could chalk up to the whole file being one giant syntax error, but it does seem to be missing that C# icon so it's probably not configured
yeah the C# devkit is the diamond shaped one usually sign of no Unity plugin installed
So @delicate slate configure your !ide first and foremost so you can see what the errors are
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
ok what one do you reccomend i click on?
The one you are using
oh
this still doesnt work as intended.
the Rotate part only works once and then never again. idk why bc i get te logs as intended
the enemy starts with a y rotation of 0, and once the rotate is triggered, it becomes -180, but by 0 + 180 i expect it to be positive.
enemy.localEulerAngles += new(0, 180, 0);
transform.Rotate will rotate by the amount specified. so if you want to rotate 180 degrees around the Y axis then you do transform.Rotate(0, 180, 0), don't add the localEulerAngles to 180
well you've got Nans in your rect transform...
🔼
this hasnt happened until after i opened unity after saving it whilst logging off one day
What does "I checked the poisitions and it won't move" mean
how's that a canvas tho? they can't be resized
Maybe try resetting the component
how do i reset the component?
Press this
well im just saying my entire canvas is corrupt. its children's positions are broken and i cannot change them
oh just saying , showing us the canvas then would've helped as well
DISREGARD THIS
everything is fine now!
thank you
ah, i shouldve done that
sorry
no worries, at least its solved 🙂
Component not inspector menu
Are there any good tutorials on how to store the position in a save?
Helloo
I have an issue
It's a problem that started happening more or less at the beginning of the last year
I didn't worry about it because wan't that of a deal, but now it's just a pain to configure sprites
Whenever I create a new Unity project and import every size of sprite, they will look tiny, having the need to escale them with pixels per unit, what end up with pretty bad results controlling those sprites with code
this is a code channel
sure
how do i make it so that when i hover over a button, a method is carried out which sets a game object in the scene as active
and then when i take my mouse off the button it sets the game object as not active
so its disappears
use a component with the IPointerEnter/ExitHandler interfaces or an EventTrigger component
can somebody please help me code a snowboard game im pretty new
help you how?
better get learning then
theres no tutorials for it
did you even look ?
yes for a snowboard tut
you're not gonna find the exact specific thing..thats just a combination of different things you learn individually
wait wait so your saying to learn other tuts to learn to make it
yes thats how everyone does it
ooooooh
If there were a tutorial on how to make exactly the game you want to make, you wouldn't need to make it
other than learning blender, is there any way to find a 3d model for a curved arrow i can use for my project
Don't just watch em, follow them!
ok
There's lots of websites with free models, but for really basic things like that, it never hurts to learn how
yeah ik but im low on time
This is a programming channel
keeps on giving me bows and arrows
ok tysm!
Then google better
forgot my bad
ima make a board and use a 3d movment script to make it move 🙂
item.mr.materials[1] = item.craftableMat;
why isnt this line of code working?
it doesnt seem to change it when i run the code
Because materials is a copy
GameObject[] floors = GameObject.FindGameObjectsWithTag("floor"); // array that gets all floors
anyone know how to change "floor" to something that would destroy all instances of this prefab? [SerializeField] GameObject floor; I want to make it so I don't have to set the tag for the floor prefab
how would i fix that?
spawn them inside a list
oh good idea thank you
Modify the copy and then assign it back to the source
how would u do that, sorry?
var materials = item.mr.materials;
materials[1] = item.craftableMat;
item.mr.materials = materials;
thank you! and why do i have to do this isntead of just assigning it directly? i know its a copy but why is it a copy?
just for like knowdlege
Because the memory that holds the original materials array not managed. Generally many things returned by Unity's properties are copies because of that. Almost every array will be at least
how do i make a varient/bool/etc that retains value between codes?
like i can change it on one code and react to the change on another
What do you mean "change it on one code"?
Do you mean instance of a class or component?
in my case is identifying if the player is alive or dead with "playerDead"
i have a code for a monster that can kill the player but am writing a separete code for the checkpoint to take action
use an event instead of relying on constantly checking a bool
ill look it up, thanks!
so im making an inventory system and have to redraw the whole inventory UI every time it updates, how much does it matter?
is changin the event as simple as =true =false? or does it have its own commands
you wouldn't change the event. you invoke it
use the profiler if you have performance concerns. this also doesn't really sound like a code issue
hello guys
void Start()
{
Instantiate(cubePrefab, new Vector3(Random.Range(-10,10), Random.Range(-3,3), Random.Range(-10,10)), Quaternion.identity);
}
what is problem?
It's spawning too many cubes
you're probably spawning an object with this script on it. So it spawns itself, then spawns itself, then spawns itself
Don't reference itself, put the script on a different object or have some way to evaluate if an object was instantiated once already.
Does the cubePrefab have that script on it?
To fix it, don't
I want to make a procedurally generating 3d dungeon, what is the best way to do this? I want to do it where I just have a floor, wall, and ceiling prefab that are instantiated to make rooms and corridors but im not sure which methods/algorithms I should use to do it. btw I have googled and watched videos and stuff and I am still having trouble so please help. I just spent like 2 hours learning and coding perlin noise stuff and it doesn't work very well and I don't know how I would make it work
why can't I see button on canvas
In the scene view you mean? It's so small I can't tell anything.
Show a screenshot that actually shows what you're expecting to see?
Show what you've tried and what results you got
I already deleted all of the stuff I had on perlin noise because it wasn't working and im trying to find another way, but ill try and replicate what I had before, one sec
does anyone have a third person controller script every tutorial didnt work
If every tutorial did work, then what's the problem?
mb
you should specify what you actually tried, and what did not work
youtube tutorials are generally shit, but they at least get the player moving.
none of them were specific enough
and i did one that did work but it wouldnt work with my player model
it just made the model roll around
@soft canyon Did you look at marching cube algo, or wave function collapse?
Maybe you should've asked about that then
Your question isnt specific enough then for what you actually need. There 100% are tutorials out there which will work for you. Your model should have literally 0 affect in this. Follow the tutorials more closely
You likely forgot to lock an axis, or your model is simply facing the wrong direction
do you have any reccomended tutorials?
what changes between scenes exept from the skybox?
is this a riddle
nah its a question lol
The name of the scene!
No i didn't i'll look into those now
can u give and example of how this changes stuff pls
- Static Batched Meshes
- Baked Static Occlusion Culling
- Baked Lightmaps
- Environment lighting
The scene itself.🤔
What kind of question is that?
I don't really understand the question tbh
ok but what is "the scene"
A collection of GameObjects
plus all this
additional loaded stuff
I just did control z a bunch to get my code back and now something is breaking and I don't want to spend half an hour fixing it just to show bad results, but this is pretty much what I had before and it was placing a grid of tiles, some floors and some walls, but I don't know how I would turn that into what I need it to be which is rooms and hallways
its that i want to make a jumpscare and tought scenes would be better than just changing cameras
Might want to go over the basics of working with unity.
ik...
@rain tartan
If you register in Awake, every object would have at least been register when start is called.
you can make your whole game in a single scene assuming you want to deal with deloading stuff manually
ah
I know, that’s how I have it setup now, but then how can I guarantee that it loads before the values are used in start?
wdym by changing cameras?
Are you talking about a FNAF game?
no, the jumpscare would benefit from a player camera
What?
@rain tartan https://docs.unity3d.com/Manual/ExecutionOrder.html shows the order of functions
bad english
"benefit from a player camera"?
jumpscare would be from diferent camera angle
A different camera angle is not a different scene
it's just a different camera or Cinemachine virtual camera
A different scene doesn't make any sense for that
Thanks? I’m aware… this doesn’t really help?
@deft siren I feel like you just want a different view for jump scares. You can enable and disable cameras in order to switch from them via scripts. This will change the view when you need to switch for the jump scare.
yeah thats it, ive already done it b4 but was wondering if there was a more "clean" aproach to it, thanks anyways!!
How do you place an image or sprite on top of a 3D object and hide the 3D object or how to replace the 3D object with your sprite?
Not a coding question. Sprites are just planes, so you can place it wherever you want to block a 3D object.
Thanks, I'll try that
You should definitely be using version control so you can separate out experiments and know what you did before.
But I'm thinking you may want to separate the floor and wall code. You could do perlin or something else for the floor code, but you'll want to build the walls around that result, not with the same algorithm I THINK.
Others will surely know more though, I have never done anything like that before
yeah that's what I was thinking of doing next, im planning on just generating a floor plan and then generating walls wherever there is a floor and nothing on the other side of it to make an outline around everything
Yeah, exactly what I was thinking. Best of luck!
Do I need to learn C# in advance or can I work with both and learn along the way?
You can learn both
idk if i understand it correctly, but OnTriggerStay does code for aslong as a specified collider is in it and stops as soon as it exits? also, in the docs it is said that its called once per physics update. what is the difference between physics update and normal update?
OnTriggerStay will keep running as long as it detects a collision. As for physics update, it's FixedUpdate: https://docs.unity3d.com/ScriptReference/MonoBehaviour.FixedUpdate.html
ok, im a bit confused about what to put in the brackets. by default its "OnTriggerStay2D(Collider2D collision)"
however this doesnt work with my player character. what would go in there?
Follow the documentation and it's examples
And if it still don't work,follow the guide on debugging physics messages:
https://unity.huh.how/physics-messages
If still troubled after that, share more details and context.
Are you using a CharacterController?
how do i add a component to my game objects. im procedurally generating object but they need to have the texture added to them. im not sure how to do this?
whats the diferrence between OnTriggerStay/Enter?
have you read what each of them are for?
wdym
ok mb ik what u mean
not really
but it seem like both are extremely similar
oh
its like a trigger that updates
!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.
what documentation
It should be your first stop with any API questions like that
what do you mean not code?
It is a command for the bot that showed right after their comment
It's a bot command. Read the bot message
yeah
Then you want to use the CharacterController method
I think it's OnControllerHit?
Or OnCharacterControllerHit?
are you wanting me to add the code?
Did you read the bot message?
It shows you how to share code
Screenshots are not one of those methods
I'm telling you to share the code correctly. Not as a screenshot.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
Can someone explain why OnStateExit is never fired?
if (Input.GetKeyDown(KeyCode.Space))
{
animator.SetBool("isSwinging", true);
}
}
public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
{
Debug.Log("On state exit called");
animator.SetBool("isSwinging", false);
}
So you want to add a component after instantiating?
There is the AddComponent<T>() method
But since you select the prefab, why not add the component to that beforehand?
so i want to add a material component to each generated object. because they are procedually generated they are all coming out gray
What kind of script is it in?
One that inherits from StateMachineBehaviour?
I don't exactly know what you mean by inherit, but animator is referenced.
public class Foo : ThingToInheritFrom
Generally you inherit from MonoBehaviour by default (unity adds that itself)
Material is not a component. It's a property of the renderer.
Oh ok, I don't think I fully understand the class system in C#. Should I inherit StateMachineBehaviour inside the existing Monobehavior class or outside the class?
Looking through your code, you are procedurally drawing from prefabs right? Or is the generation in another script?
ok so how do i add it through the code so all i have to do is drop the material into a call in unity
its the same material for all of the game objects
the code i sent is the generation
If was not procedural generation, it was procedural placement.
You randomly get a gameobject from one of three arrays of gameobjects
You don't actually generate those objects in that script though
So where do the objects come from?
So I didn't know the method you used, I just looked up the docs and saw the example code here
https://docs.unity3d.com/ScriptReference/StateMachineBehaviour.OnStateExit.html
im a dummy i was adding in the material not the prefab
i think its time for bed thanks for the help
i spent almost 2 hours on this
the link doesn't seem to be working for me for whatever reason
Huh, I did the wrong link for the example code, but it should still take you somewhere
Here is the more helpful link
https://docs.unity3d.com/ScriptReference/StateMachineBehaviour.html
I'm on a plane right now, could be United wifi tripping lmao.
I do think I was on that documentation earlier though; it was painfully vague.
Are you saying I have to move this code to a seperate, non-monobehavior script?
Looks like it, yeah
That sucks, was trying to cram all animation/movement stuff into one script.
I'll tell you if that works
However, I feel like you could just have it transition back to whatever state you were in before, or do a Trigger instead of bool
Might wanna ask in #🏃┃animation for better help
I'll also say though, you want to split scripts up more, not cram as much in as possible
Yeah definitely, but in this particular instance I felt it was more organized to consolidate it.
Can you elaborate on what you mean here?
I mean, A) letting the animator do the work with transitions, which I guess still means you need to deal with the bool?
B) use SetTrigger, not SetBool
I'm bad with animation though. Seriously just ask in #🏃┃animation haha
Wait that was it lmao
Made it a trigger and it magically works perfectly
Thanks for all your help
From what I understand, the trigger is "consumed" when used, so it toggles back? Haha
Glad it worked
Interesting. As you can see, I only found out about the animation system today so still figuring it out lol
the button is the big invisible rectangle, and it does not show
it does the job, but I want it to be as big as the canvas, the background on editor is so small, but it's so big in simulator
how to fix this please
does anyone have a link to a guide for a 4 way movement system i can only find ones that are 8 way.
The canvas would be the size of your screen in units, so it's natural for it to be bigger than the rest of the game. The button needs to have size relative to the canvas for it to be visible, not the other gameObjects.
Where can I execute this in a Unity project with 2D Tilemap/Tile Palette so that I may count how many tiles a level is long and high?
https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap-cellBounds.html
Thank you!
This time, I would like the backround image to be the size of the canvas, but when I do, it goes so big in the simulator, I want them to be relative , is there a fix? I think it's about scaling but im not sure
figured it out :)
There is no fix. Aside from maybe using a world space canvas. This is just how screen space ui works in unity. Don't consider the UI to be in the same space as your other gameObjects.
Hey, I'm using a FreeCam script I found on the asset store, my problem with it is that I would like to have multiple cameras that use this script and currently the script affects all cameras that use it.
So if I move with one camera, all other cameras with the script move with it, I'm not sure exactly why it happens. I would assume variables are shared between the instances, I'm quite new to Unity and C# (although I come from a Java background) so any explanation would be appriciated 😄
first !code
second, if it the components are enabled and they are just using the regular input manager static methods to get input then of course they will move with the input
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Oh, thats neat, sorry I didnt know about this
I mean the code thingy
why does this thing happen ??? can anyone tell me??
Could you explain in a bit more detail? Like I said I'm a complete newbie, I have like 2 hours in Unity at max
okay well i still haven't even seen the code so my second point was just a general "this is a possibility"
yeah so you just need to disable instances of that component that are not currently in use. that's literally all you need to do to fix your issue
Sounds great 😅 how do I do that?
there are beginner c# and unity courses pinned in this channel, you should perhaps start there
can anyoe help me with it
I'll check them out
I dont get it 😛
what do you not get?
you have a variable that is not assigned on line 101 of PlayerController.cs
But dont i assign it in UnlockMovement?
what do you think is on line 101 of PlayerController.cs
a declaration is not an assignment. where do you assign to your swordAttack variable
none of this code here is relevant. and please for the love of god stop with the cropped !screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
Also very new to the discord
how to post !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.
Anyone here??
Just to clarify, all I need to do is to disable the script component dynamically whenever I switch cameras?
see #854851968446365696 for what to include when asking a question
yes
Oh sweet, I'm just curious though, why was my issue even there in the first place?
All the variables are defiened inside functions and are private
Or does that not matter
because all cameras are reacting to the same Input
My problem is that why the car is just flying??
because the component is enabled so it's Update method is running. and it's getting input using the InputManager which is just a collection of static methods and properties that report the current state of the input
congrats. now see #854851968446365696 for what to include when asking for help
no one can help you if you dont paste your code and specify more about what you actually want to happen. randomly your car has like 1 million mass
also your video is like 1fps
So sir what code you want?? The Lambo (car script) or speedometer script????
shouldnt you know that? what kind of question is this lol i dont know what either of these scripts do
Oh I get it, thank you so much, I'm not sure why I even asked this question lmao, the asnwer is really intuitive, I thought it was something relating to variables

What code would be relevant?
im unsure what my next step shouldbe
the code where you assign to your swordAttack variable in your PlayerController class
This?
public void SwordAttack() {
LockMovement();
if(spriteRenderer.flipX == true){
swordAttack.AttackLeft();
} else {
swordAttack.AttackRight();
}
}
do you know what it means to assign something?
I dont think so
using UnityEngine;
public class MobileCarController : MonoBehaviour
{
public float initialAcceleration = 10f;
public float accelerationIncreaseRate = 5f;
public float steeringSpeed = 5f;
public float brakePower = 20f;
public float inertiaFactor = 0.95f;
private float currentAcceleration = 0f;
private float currentSteering = 0f;
private Rigidbody carRigidbody;
void Start()
{
carRigidbody = GetComponent<Rigidbody>();
}
void Update()
{
// Acceleration
currentAcceleration = Input.GetAxis("Vertical") * accelerationIncreaseRate;
currentSteering = Input.GetAxis("Horizontal") * steeringSpeed;
if (Input.GetKey(KeyCode.S))
{
currentAcceleration -= Time.deltaTime * brakePower;
}
carRigidbody.AddRelativeForce(Vector3.forward * currentAcceleration, ForceMode.Acceleration);
carRigidbody.AddTorque(Vector3.up * currentSteering, ForceMode.Acceleration);
}
}
there are beginner c# courses pinned in this channel. start there.
Now I have told my problem gave the script now atleast help me please 🥺🥺🥺
I'm begging you guys
They shouldnt just give you the answer
Wdym?
All I wanna know that where's the problem
Shouldnt something like an errorlog give you a problem
Nope
There's no at all that problem
Tell me wheres the problem (Except in my brain) I'm going....
It's a feature?
you are adding relative force, so when the car rotates upwards slightly it will add force upwards or in whatever direction its pointing
Doesn't look like an error.
how would i make it so that i can display multiple 3d items in a render texture? i know how to do one item but how would i set it up for multiple?
Anyone knows how to make a script that uses the mouse to move the camera left and right of this image
You cannot turn a Rigidbody via the Transform like that. It will break interpolation exactly as you're seeing
The rotation needs to happen via the Rigidbody
The same way you render one object. I don't see the issue
Just move multiple objects into the camera's view
That's exactly what I said yes
Im creating an essentials loader so if i enter a scene and i dont have a player object or a cinemachine camera it will load. I have removed them on a scene to test but they dont re appear. https://gdl.space/fecubiyifi.cs
they are all prefabs
have you put any logs anywhere or used breakpoints to actually inspect what is happening?
and are you also certain that there are no other colliders in your scene?
Thanks, it works now
you are checking if ANY gameobject exists with a Collider
yes i did notice one mistake it was looking for virtual cam not free look fixed that but still does not load
and have you confirmed that there are no colliders in the scene?
i mean any colliders in the scene on any object
player has a box collider
so then there is a collider in the scene, yes?
yes
so then what do you think the result of GameObject.FindObjectOfType(<ColliderTypeHere>) is?
is it null?
the debug out put was null
that is not what i asked about
you said there is a collider in the scene. So will GameObject.FindObjectOfType(Collider) return null or not
yes
you are checking whether the object exists twice. first with the tag check. then you check if any collider exists in the scene for whatever reason
thanks for help
I try to make a ray to sellect gameobjects that hit the ray, the only issue is that this doesent work waht maybe can caused by the new input manager (I think?)
var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
What would I need if I want to put my mouse delta from the new input system in there?
Error:
SoulShardsCollecting.Update () (at Assets/Game/Scripts/SoulShards/SoulShardsCollecting.cs:39)
That has nothing to do with the Input system. The error suggests you do not have a Main camera in your scene
I have a Camera but not a Main camera.
then you cannot use Camera.main can you
But now I get one because if the wrong Input System, but I fixed it by replacing it with:
[SerializeField] private Camera _camera;
private MeineInputActionBelegung _controls;
var ray = _camera.ScreenPointToRay(_controls.Player.Movement.ReadValue<Vector2>
());
Have another question i have deleted the player from the scene to test that it gets cloned that works. but it breaks my cinemachine free view. So i have attached a new script that adds the folloe and look at like so..```public class CheckCameraTargets : MonoBehaviour
{
public Transform playerTransform;
private void Awake()
{
Cinemachine.CinemachineFreeLook freeLookCamera = GetComponent<Cinemachine.CinemachineFreeLook>();
// Check if the Follow target is null
if (freeLookCamera.Follow == null && playerTransform != null)
{
freeLookCamera.Follow = playerTransform;
}
// Check if the LookAt target is null
if (freeLookCamera.LookAt == null && playerTransform != null)
{
freeLookCamera.LookAt = playerTransform;
}
}
}``` the camera works but does not follow the player when he walks. i feel like its coming from my player controller and its using the camera https://gdl.space/isagesized.cs
but i can confirm that the cam object is attached to the field
Could it be an order of execution?
hello! Im looking for a way to reference a class that has no namespace from a class inside of a namespace, how would I do that?
Ive tried this
GetComponentglobal::GrabbableItem()
but Im getting an error
Ok, making "Selecting Objects with Raycast" is way to complicated, I think I just put a 2 meter long small invisible cube in front of the camera and make a OnTrigger Event if it touches a interactable gameobject.
any one here knows visual scripting?
this will however trigger through non-interactable too
so you´d be able to interact with stuff behind walls etc
- I wish I would know how to make the code foldable in discord...
Its always taking so much visible space
then post it properly, you've been on this server long enough to know how to do that
No, otherwise I would not asking.
I just know this "``````cs "
But it never was the main issue. its mostly the Unity relealted toubles and bugs but it would be nice to have to know how you make foldable codeblocks.
what? you've never seen !code? It's only put up here 100's of times per day
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Ok its not telling me anything I didn't know already.
I meaned to make a foldable: ```cs
// Your code here
In Discord without external website.
so you have to click on it to open its full size
doesn't exist, so use the tools that do
Any idea why this Selecting Objects with Raycast doesn't work or at least work only if you are close to it and look 90° to the right of the sphere?
It turns also blue if the player is not close enough what should not be cuased by the code because there is no lenght-raycast yet...
(Blue is standard color, yellow is highlighted color)
https://paste.ofcode.org/nacQrjFKCuFp9h874zj8MU
I wanna get this result, what i did wrong?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMove : MonoBehaviour
{
public float sensitivity = 2f; // Adjust this value to control the mouse sensitivity.
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * sensitivity;
// Rotate the camera horizontally based on mouse movement.
transform.Rotate(Vector3.up * mouseX);
}
}
hi im trying to use mouse to navigate left and right of a png image but how do i stop the camera from going out of the image
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class PlayerMovement : MonoBehaviour
{
public bool hasJumped;
public float coyoteTime = 0.2f; // Time Window for Coyote Time jump
private float coyoteTimer;
public float jumpForce;
private Rigidbody2D body;
// reference to layers
[SerializeField] private LayerMask groundLayer;
private void Awake()
{
//grab references for components of the game object
body = GetComponent<Rigidbody2D>();
boxCollider = GetComponent<BoxCollider2D>();
}
private bool isGrounded()
{
return Physics2D.BoxCast(boxCollider.bounds.center, boxCollider.bounds.size, 0f, Vector2.down, 0.1f, groundLayer);
}
void Jump()
{
hasJumped = true;
body.velocity = Vector2.up * jumpForce;
}
private void Update()
{
// //reset or start coyotetimer
if (isGrounded())
{
coyoteTimer = coyoteTime;
hasJumped = false;
}
else
{
coyoteTimer -= Time.deltaTime;
}
// (wall)-jump and doublejump/coyotetimer check
if (Input.GetButtonDown("Jump") && (isGrounded() || coyoteTimer > 0))
{
Jump();
}
}
}
can anyone explain to me, why my char is sometimes able to doublejump? I thought that with the "hasJumped" i could fix that. But apperantly. If I spam space often, sometimes the char doublejumps
Well clearly its because either one is true isGrounded() || coyoteTimer > 0, so start by logging which one is true inside your if statement when you expect it to be false. Then you can start figuring out why they are not the value you think they should be.
also you don't use the hasJumped variable anywhere
it is the coyoteTimer that is true, because of my if (isGrounded()){coyoteTimer = coyoteTime;hasJumped = false;}else{coyoteTimer -= Time.deltaTime;}
Yep, I noted that. I just added it : if (Input.GetButtonDown("Jump") && (isGrounded() || coyoteTimer > 0) && !hasJumped)
still not working
I got a debug text that returns "isGrounded/isNotGrounded" So I can tell that when I get the double jump in air its definitely not because of the "isGrounded" statement
the issue does not occur with if (Input.GetButtonDown("Jump") && (isGrounded() /*|| coyoteTimer > 0) && !hasJumped*/))
this system works differently.. ur not actually rotating the sphere RB... ur setting the position of the graphics to the rigidbodies position.. and then you rotate the car.. the rigidbody just gets its direction from the car's facing direction.. the rigidbody just rolls (always facing the same direction) but rolling in the direction the car is facing its a roller ball with a car skin lol.. if u want to rotate the actual rigidbody you need a different setup. if u keep it how it is you can just turn on interpolation on the rigidbody.. it will smooth out the graphics a bit.
You need to move the mouse following object via Rigidbody2D.MovePosition in FixedUpdate
hi guys. i followed this unity documentation tutorial on how to make nav mesh agents work with root motion(by that i mean copy pasted) : https://docs.unity3d.com/550/Documentation/Manual/nav-CouplingAnimationAndNavigation.html
and my nav mesh agents movement has become extremely jittery.
at first i thought my animations were the cause of this but then i checked the values and, deltaPosition is the cause. this vector 2 is jittery also causes smoothDeltaPosition and velocity to become jittery. any idea why that is and how i can fix it?
https://hastebin.skyra.pw/ohohilexas.csharp -> SynchronizeAnimatorAndAgentRootM() function line 71
thanks!
The Unity Manual helps you learn and use the Unity engine. With the Unity engine you can create 2D and 3D games, apps and experiences.
can i add FixedUpdate method into my script manually?
How else would you add code to your script?
You kinda have to, to use it . . .
using keyboard. I'm BIG begginer in unity and guess it doing somehow in rigidbody component. Thanks for help, i'll be back with new problems
apologies if this is the wrong channel. this is my first time trying to create anything in unity. i started with a 2D project.
i did the configuration of Visual Studio Code to Unity, did coding, attached the script to GameObjects, but whenever i run my build, it will start up on a blueish screen. it's supposed to show a black screen with white text.
i've tried making the main camera the same position as the canvas UI, i've tried changing the solidcolor to Black in the main camera, tried changing my render settings to several different things, tried setting the hierarchy in several different ways...
it's been two days of no progress due to me being unable to figure this out on my own...
please help?
Show us the inspector for the canvas.
The default mode, "Screen Space - Overlay" doesn't care where the camera is. The canvas is just rendered directly onto your screen.
Did you add your scene to the build settings?
i'll show both of you screenshots of the settings, it's just taking a second to start up
I think this should be correct?
Now I can move objects how I need, but them can be thrown out the screen. How to prevent that?
You should go and watch some basic unity tutorials first
Would save you a lot of time understanding things
That is a code related channel, if you have any issue with code you can ask here
Anyway, change your collision detection mode
^ make ur detection continous
ty
could also probably beef up the colliders on the sides of hte screen (if that is indeed whats stopping them)
i'm not a designer, all i know is coding
ur using a graphical interface.. therfor whether u like it or not ur designing
Could it be like his area is bigger?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UILobby : MonoBehaviour
{
[SerializeField]
InputField joinMatchInput;
public void Host()
{
}
public void Join()
{
}
}
this is my code and i am traing to put an input field in there but it wont let me drag and drop it
so he could reduce it a bit
you probably created input field from text mesh pro
i am new i don't know much
and you make variable of the legacy input field type
sorry
i dont think his area has anything to do with it.. he doesnt have a designated area where the items can be clicked or moved.. he could program it that way.. so if the mouse position is off the side of a threshold stop it or drop the item..
but right now i think its b/c hes moving the rigidbody so fast it clips thru the colliders on the edge of the screen
raising the detection to continous will probably allow it to not pass thru
yes
Today i got to code different mouse clicks.. like if this is selected and u click it it will do somehing.. if u click and hold it will do something different.. if u click and drag it'll do yet something different 😄
i can see a future of ugly ass nested if statements
can i change this in a way
change the variable type
to match the input field from text mesh pro
thanks
TMP_InputField i believe it is
atlesat give people opportuninty to google things themselfs and learn something 😄
otherwise he'll just copy&paste
lol, i said "i believe" if he's attempting to learn he'll still need to confirm
most people would just copy paste it and if it will work then they dont need to confirm anything
i just got here.. it can be my test..
if he returns ill know not to next time
lol
i may.. end up making my click script a statemachine..
so depending on wether its a click and release.. or a click and hold.. or w/e it'll transition into a state that returns different things..
Not a solution, but a bunch of other people here had problems with that example too. That Lerp it does is super strange and jumps up and down like mad. No idea how to fix it.
does anyone know 
i refuse to work with root motion
What happens if you just force deltatime into it? Or a constant value?
how?
i sadly need it for knockback animations, like the zombies in left for dead when you shoot them
you can just make the animation walk in place
and push it by code
thats what i was always doing
cba working with root motion
it has so many issues
i know but this eliminates foot sliding without the need of ik
what's the issue of implementing ik?
you'd have done it much faster and easier
than "having fun" with trying to make it work with root motion
my animations are all walking in place, and im knockbacknig the enemies via dotween
- ik
i dont want my npcs to just slide back, i want them to rotate and move with the animation, and their movements arent linear
unless its super crazy rotating animation with different randomized movement
you can achieve all that with dotween
or just your own code
well i wont cuz im stubborn and i want to do it this way 🙏
an answer to my original question would be appreciated however
here's a stupid problem: I just want to rotate a sprite 90 degrees every using animation event triggers. I figured this would be a no-brainer since I already have triggers in other animations and I have a function to flip the another sprite.
Here is an image of my sword sprite, the animator with trigger events visible:
And here's the code I thought would work (this script is attached to the Sword game object with the animator component)
How did I mess this simple task up?
ah...makes sense
ok mb
First step is add Debug.Log here and see if the code is running
also check the console window for any errors
A screenshot of the Animation Event configuration would be helpful too
alternatively you could just do it without animation events
just rotate yourself and record the animation
Well yeah the animation itself could rotate the sword rather than using events
in events you could play a audio clip or something
but rotation through code in animation is kinda off for me
hit the record red button and just rotate it 90 degrees every X frames
actually, my original code was working, but it only works when playing the game (I can't preview the events when I just play the animation in the Animation window. No 💩 , huh?
I also correctly guessed that transform.rotation*=Quaternion.Euler(0,0,90) would work, but it's the same outcome
well yeah of course it only works when the game is running...
hence "No 💩 , huh?"
oh yeah, sorry my brain is bad at reading emojis
I need help with unity can someone help me?
Just ask, you don't need permission to ask a question
oh okay
Unity's animator is breaking every time I change a script (doesn't matter which one) or really make any changes at all to the project. I am aware that I can close the Animator window and reopen it to temporarily solve the problem, but this is getting annoying. It happens eventually whenever I start a new Unity session too, so restarting Unity isn't a permanent fix.
NullReferenceException: Object reference not set to an instance of an object
UnityEditor.Graphs.Edge.WakeUp () (at <5675beb25788478c930377bea67fb893>:0)
UnityEditor.Graphs.Graph.DoWakeUpEdges (System.Collections.Generic.List`1[T] inEdges, System.Collections.Generic.List`1[T] ok, System.Collections.Generic.List`1[T] error, System.Boolean inEdgesUsedToBeValid) (at <5675beb25788478c930377bea67fb893>:0)
UnityEditor.Graphs.Graph.WakeUpEdges (System.Boolean clearSlotEdges) (at <5675beb25788478c930377bea67fb893>:0)
This only started about a week ago
I get this so frequently, it's wild.
Yeah... just a Uniy editor bug. Best you can do is report it, keep up to date, and hope they fix it
closing the Animator isn't preventing the problem anymore, it just shuts it up until I change something
ok
every time I start the game I've made in there and I put my VR on, it just goes into computer mode instead of you being able to play the game you've made in VR
Know what, might be because one of my animations in the Animator doesn't have a transition for it to start yet
I'll get to that in a few min and see if that shuts it up
thank you just text be then
i have a script on a parent and want to reference the animation event of a child, how do i do that? i cant seem to find an answer
what do you mean by "reference" the animation event?
like when i make an animation event, i want it to pick up the script
Put a script on the Dust object with a function which calls a function in the script on ArrowBreak
call that first function from the Animation Event
aight
didn't work, fyi
Will anyone help me in a private call
no
wwhy
where then
every time I start the game I've made in there and I put my VR on, it just goes into computer mode instead of you being able to play the game you've made in VR
Probably nowhere that's a pretty unreasonable thing to ask
Ask that in #🥽┃virtual-reality and provide information about your current setup
How do I get Classes etc to be recognized by visual studio? so they get a different color and such
like Vector3 etc
!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
legend
Good morning everyone , I have a general question to start with. My projectile should control the amount of damage it does correct?
Of course
That seems sensible, if that's what you need to happen
Ok so I want a power up to increase damage by a percentage , how would I go about changing that with every bullet fired?
Getting the bullet controller of currently fired bullet and adding to the damage each time I spawn the projectile
you should probably write system that allows projectiles and attacks to carry payloads of various effects
with damage calculated on hit
or not, i imagined you have various status effects based on what you said, but maybe the powerup is something simpler
sounds good to me.. ur projectile (just like anything) should control the things relevant to it.. so the speed its moving, the damage it inflicts, etc..
interactions are when u can pass data. soo when the projectile hits something you can pass the damage thru that function to a health script for example.. and it can read the damage from the bullet.. and subtract it from itself, and so on
Can't add script component 'MatchMaker' because the script class cannot be found. Make sure that there are no compile errors and that the file name and class name match.
i get this error when trying to drag a script onto an empty object
what is the name of the file
Follow the instructions in that error
Hello
its in the error
that means that there are either
- compile errors
- the name of the script doesn't match the name of the class
that the file name and class name match
So i have a beam overlapping onto 2 cubes at either end and i have to add a fixed joint where it meets. however the joint is only being attached to one of the cube, am i missing something?```void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Support"))
{
Debug.Log("Hinge Attached");
FixedJoint fixedJoint = rb.gameObject.AddComponent<FixedJoint>();
fixedJoint.connectedBody = other.GetComponent<Rigidbody>();
fixedJoint.anchor = transform.position + new Vector3(0, 5f, 0);
fixedJoint.connectedAnchor = other.transform.position;
}
}```
Again thanks Digiholic, it works now
looks mostly correct on first glance.. make sure they both have colliders and rigidbodies.. it may be an issue w/ the colliders with each other..
not sure tbh
``
this is my code
i summon thee. Come! !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 need three backquotes at the top and bottom to format into a codeblock
okay
using System.Collections.Generic;
using UnityEngine;
using Mirror;
namespace MirrorBasics
{
[System.Serializable]
public class Match
{
public string matchId;
public List<GameObject> players = new List<GameObject>();
public Match(string matchId, GameObject player)
{
this.matchId = matchId;
players.Add(player);
}
public Match() { }
}
public class MatchMaker : NetworkBehaviour
{
public static MatchMaker instance;
public SyncList<Match> matches = new SyncList<Match>();
public SyncList<string> matchIds = new SyncList<string>();
private void Start()
{
instance = this;
}
public bool HostGame(string _matchId, GameObject _player)
{
if (!matchIds.Contains(_matchId))
{
matchIds.Add(_matchId);
matches.Add(new Match(_matchId, _player));
return true;
}
else
{
Debug.Log("MatchID already exists!");
return false;
}
}
public static string GetRandomMatchID()
{
string _id = string.Empty;
for (int i = 0; i < 10; i++)
{
int random = Random.Range(0, 36);
if (random < 26)
{
_id += (char)(random + 65);
}
else
{
_id += (random - 26).ToString();
}
}
Debug.Log(_id);
return _id;
}
}
}```
please use a paste site.. when the code is large https://pastebin.com/rH4Xv83t
i play DynoBot in attack mode
i did it for you this time
no worries..
so when i try to drag it on an empty object it wont work and i dont really understand why because all classes seem to be correct
no from netwrokbehaviour
MatchMaker and as long as the script is MatchMaker.cs the name part is good
Make sure that there are no compile errors and that the file name and class name match.
^ thats the only two reasons it would not work
Hmmm they both have colliders and rigidbody
the file name is MatchMaker.cs
What is the file name of this script
ah beat me to it
Show a screenshot of your console
thx i think I know the problem let me check
(Blue is standard color, yellow is highlighted color)
Why is this offset so weird on my camera?
Why is it only selecting the object if the camera looks 90° to the right side of it?
Using the joystick position as a screen point is pretty strange
IDK what it is for, normally "Input.mousePosition" would be used for this but I use the new input system.
IDK what for and this docu is not helping me.
I tried to follow this tutorial and this dude also used the mouse.
Is it wrong to use "Input.mousePosition"?
Sign up for the Level 2 Game Dev Newsletter: http://eepurl.com/gGb8eP
This Unity tutorial will teach you how to select objects using raycasts.
#UnityTutorial #Raycast #GameDevelopment
📦 Download the project at https://www.patreon.com/posts/25656838
This tutorial was created in part with Jason Storey (apieceoffruit). Learn more about Jason b...
It tells you what screen point to ray does since you said you didn't know what it was for
Did you try looking up how to get mouse position in the new input system