#💻┃code-beginner
1 messages · Page 70 of 1
Is there a way to use integers as degrees instead of radians in Mathf.Sin?
I see, in that case I'll just use an overlay space, that's easier to change imo
Thanks for the help
For example if I have an int Angle = 90
I want to be able to calculate a Mathf.Sin(Angle) that equals to 1, and not to whatever the sine of 90 radians is
Hi. I need to display some calculations on my screen, and I want to show some of them in degrees. The problem is taht unity calculates perfectly sin and cos in radians but I cant get it to convert them properly to degrees. I’ve used the Rad2Deg variable, and even try it by the “manual way” like this: cosOps=(360Mathf.Sin(45))/2Mathf.PI; Than...
Mathf.deg2Rad
There's two constants, Mathf.Deg2Rad and Mathf.Rad2Deg that can be used to convert one into another
Multiply angles with these to convert
and this
thanks, this seems to be what I'm looking for
hmm now it seems to work correctly, except for 180 degrees for some reason
the Mathf.Deg2Rad converts it correctly to 3.14159
but then it returns some weird value when I get the sine of that
-8.742278E-08
I have no idea how that even happens
Very close to zero that number is
It's scientific notation
-0.0000000874 or something
Yeah
ah alright I'll just round it to zero then
What weird value?
I read this in Yoda voice
Yeah I started writing this, realized the sentence was going to be backwards, but finished it anyway
Instantiate(blood, this.transform.position + bloodOffset, Quaternion.identity, this.transform);```
I'm instantiating a particle here
I want the particle to follow "this"
but I do not want it to rotate with it
Is there any way to lock the rotation?
I think try looking into the Parent constraint component
any other/easier way?
Set the position in update instead of parenting
Not sure how it could be easier than just attaching and configuring a simple component
the object it's attached to is a prefab
anyway I figured it out, you can just set the simulation space to world instead of local
That doesnt make the particles follow you but it makes the emitter follow you
yeah that's what I meant/wanted
That's a totally different thing than you asked for though
yeah I meant particle system instead of particle, my bad lol
the semantics get confusing sometimes
if the ghost (green) is moving towards the player (black), how would I have it go around the circle collider (which is currently a trigger, I might be able to convert it to a normal collider? though that'll require wrangling other aspects of the ghost's behavior) at a consistent speed. so far I've set up a system that when it enters, I push it directly out of the collider - though this results in heavily varied speeds as it moves around the circle. I'm halfway through setting up some rather convoluted equations using a cord of the circle with length calculated by the ghosts speed and heavy wrangling of the internal angles. but I feel like there's got to be a better way than this
typically the ghost's behavior is to move directly in the direction of the player (using movetowards)
how to build an android game
open build settings switch to android
try to build it and wait
look at the first error, google it, try to fix it
if after an hour you still can't figure it out, come back here and ask
repeat until it works
Hi everyone I have a question. Do you know how I can get the X Y Z rotation of an object because when I use eulerAngles for the rotation 180,0,0 i get in console 0,180,180. Do you have a way to fix it ?
There's nothing to fix. Those are the same rotation.
not too familiar with eulerAngles but would transform.rotation not work?
that's a quaternion
a lot of time with stuff you don't understand it's way better in the long run to just push through and learn it, rather than going against the flow by avoiding it. Quaternions are definitely an example of this.
okay i gonna follow your advice
there are lots of resources online for quaternions, one that immediately comes to mind was a GDC talk from either last year or the year before that
You don't really need a deep understanding of quaternions at all
Just understand that they are rotations and learn to use the helper methods (AngleAxis, LookRotation, FromToRotation etc)
turns out the talk I was thinking of just has the slides available for free, rather than the full talk. but they can still be helpful
https://www.gdcvault.com/play/1027047/Math-In-Game-Development-Summit
All you need to know is it's a type of variable that contains a rotation
It's really not needed to understand the underlying math
thank you very much to all
Nice! Do you feel like it cleared up any of your confusion?
when visualstudio says a line of code is obsolete, does it means it's less efficient?
No it literally just means someone put the [Obsolete] attribute on it
what
Developers usually do this to indicate there's a newer better thing you should be using instead
like, enough people said its obsolete so the program thinks it is
No
oh alright
The person who wrote the code you are calling
Code is not a democracy lol
alright thanks
using Microsoft.Unity.VisualStudio.Editor;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeadTimerUIScript : MonoBehaviour
{
[SerializeField] private Image reviveTimer;
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
SerializeField is not in the inspector
That's probably Image from a different namespace
Compile error
wrong Image type. you should be using UnityEngine.UI.Image
kinda
now i know classes, enums, and that stuff
That all happens in one frame
Try a coroutine or a timer
Yeah both if statements run here
but i'm still not sure if that's enough
Thanks
i'll still try games in 2d to make stuff easier
That is definitely a good start.
Just knowing the breadth is a good start, now you know your options.
Is there anything that is specifically still confusing
no, i have understood basically everything (i think)
but still i feel like i am missing something
Yeah, it will definitely feel that way for a while.
Come back with questions when you need.
Follow some small FULL tutorials to make different small games.
Work on your game to get experience.
It'll just take time.
ty man, i appreciate that
i'll take it slow though
i don't want to rush things and get to a burnout
That's wise haha.
i'll try small things and slowly get to bigger ones
see ya :)
hey everyone, i am trying to set my coin so that when i collide with it, i increment an integer (score), yet when i collide with it, nothing happens
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Coin")
{
// Coin collected
totalCoinsCollected++;
Debug.Log("Coin collected! Total coins: " + totalCoinsCollected);
// Destroy the coin
Destroy(other.gameObject);
}
}
ive set it on my gamemanager, and set the tag of my coin to , well ,coin
Do you get the debug log?
first dont use == for compare tag, use .ComapreTag()
second log if the method is fired
is one of them has rigidbody?
i dont see it logged at all, thats the weird part
and yes, i do have a rigidbody on player
Try with the log outside the if statement to see if the method is getting called at all
gotcha, will do that rn
it is not fired at all , and the body is colliding (dont ask how i messed up the character lol)
Follow the troubleshooting guide here
Apply the fixes if needed, and if you still don't get an execution then hit "I am still not getting a message" at the end of the page
will do
My UnityEngine.UI isnt recognized? Edit: fixed by reloading with unity? idk what happened
does the error only appear in visual studio? if yes, regenerate project files and restart it
I have come to brag using c-sharp 11 on unity 2017 
I mean, you'd only get access to the syntax sugar stuff from newer versions of c#. you're still limited to the features of the .net runtim you are targeting in the unity project
and are you attempting to use something that isn't just syntax sugar? if not, i never said it wouldn't compile
all those lines are game objects ? 😬
just heirarchy EditorOnly separators
does this count as simply not just syntactic sugar?
lemme try switch expression thingy
is that one counted too?
i cannot see the circle even though i set its color as white
both are syntax sugar
any example of what's not?
ps: the color is white even itself, i put this script to fix it but it didn't work
its probably not infront of the camera
it's in the middle of the screen
that doesn't mean its infront
click the ball, send the screenshot
the object has no z value
i bet you can't index an array using the index from end operator ^
how to write that, idk ^ operator yet
myArray[^1] gets the last element of an array
how do i solve it then?
Is it behind your background?
oh does ...somethingHere counts as non-syntactic?
i think so
i remember seeing it a lot before
i tried to remove it and it showed a gray object
is your background an image?
Use Sorting Layer / Order in Layer to fix it then
yep
okk
use Z position as well works sorting
ty
that looks like it is supposed to be the range operator so if that's what it is then yeah
Try static abstract members in interfaces, that's not syntax sugar AFAIK
this does not work ig
yea range operator is what i remember it's called
yeah. so you only get the syntax sugar so it was mostly pointless to force c# 11 to work in your version 🤷♂️
Yeah it does not bring the new types in
new types like?
System.Index
hey guys i have a question. I have a simple menu with the button "play" on it. when you click it you go to the "level 1" scene. is there any way i can re-use the code to make it so when you click an specific spot of the level 1 you go to "level 2"? i can send my code here.
sure
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class Menu : MonoBehaviour
{
public void Jugar()
{
SceneManager.LoadScene("SampleScene");
}
public void Salir()
{
Application.Quit();
}
}
Make a public string for the name of the scene you want to load and set that in the inspector
just increase index of level
I should, make a new script or modify this one?
modify that one
alrighty
now i just gotta figure out how to do that, but i think i know how.
anyway, me is more than happy having pattern matching alone, no more weird pattern like this
actually lemme try if i can do a tuple
fun fact but the pattern on the bottom basically just compiles to what you have on the top
tuple should work at least, though idk how to write one
considering Tuples were added in .net framework 4.0 and 2017 uses a slightly more recent version then yeah, they work. and they even worked before
did i use it wrong then?
I wonder if records are supported by your thing, they're good for prototyping and get expanded into classes/structs anyway
record Sample();
record struct Point2D(int X, int Y);
sorry
var tuple = (32, 5);
I fdup
forgot how to do named tuples xD
i just use structs 😦
yeah that syntax that was provided was a ValueTuple not a Tuple (slight difference). that wasn't added to .net until .net 4.7 which i'm not sure if unity 2017 uses 🤷♂️
record does work
unity17 is 4.6 .net
how to make the ball moge in a random direction (making pong)?
if you want physics, use addforce
Character Controller was in front of my mesh collider, sooooo it never did collide
im trully a genius
add slight degrees offset to Vector3.reflect maybe
or you mean the beginning ball
that
i'm surprised this works. i was under the impression that records required the init language feature to work. though i guess it does just compile into a class or struct
do i have to use a range or something?
var direction = Vector2.right;
if(Random.value <= 0.5f)
{
direction = Vector2.left;
}
//apply direction```
vector2?
same thing
is there a non-syntactic feature latest unity c#(9) can do that i c#6 couldnt?
okk thx
oh, random direction, isnt it better to use RandomInsideunitcircle for extra added flavor?
i have no idea
you are the experts lol
not even an expert, but it will make your ball like go at an unexpected direction at start
Random.insideUnitCircle is a vect2
yeah i wanted to ask that too but i didn’t want to bother you too much
literally any feature that requires a type introduced in a more recent .net version is something you cannot do. like the range and hat operators
how can i reference one script inside another?
ty
zombie's patch literally grabbed latest roslyn files into unity though
public void TimerStart()
{
currTime = 1;
reviveTimer.fillAmount = currTime;
while(true)
{
print(currTime);
currTime -= Time.deltaTime * 0.01f;
reviveTimer.fillAmount = currTime;
if(currTime <= 0f)
{
cancelButton.onClick.Invoke();
break;
}
}
}
}
why is the timer instant at 0?
that doesn't upgrade unity's .net version though
loops run to completion. since this is neither async with an await nor a coroutine with a yield there is nothing preventing this loop from completing in a single frame
if this is being called from Update or something then just remove the loop entirely
You're one of the lucky ones that make a loop that will actually exit all the time
hehe 
changing that will also not update unity's .net version
no its called from an onTriggerEnter
then read my first message
a very short word that is very deep topic in c#
why is my WHITE ball gray?
i think i'll just draw it
it looks better tbh 
why does it have a mesh material on it instead of a sprite
also this isn't a code question
_childRectTransform.SetParent(transform);
_childRectTransform.position = Vector2.zero;
Is the first line not completed within one frame by any chance? Because it still positions the element at vector zero of the old parent, not the new one
This is in `public void OnEndDrag(PointerEventData eventData)´
do localPosition
instead
oh wait no
anchoredPosition
_childRectTransform.anchoredPosition = Vector2.zero;
Ah yes, cheers
!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.
hey, does someone know why fog doesnt correctly works?
it just makes an strange halo on the road
https://gdl.space/tuzifeyove.cpp Can anyone help me figure out why line 26 is not working in my code? Player 1-4 are not being added to my list, should i be using a different Method other than add? or a different parameter other than FindObjectWithGameTag
Not a code question => #archived-lighting
FindGameObjectWithTag only returns the first object it finds with that tag. But you should use whatever spawns those to add them to the list when they are spawned in the scene
it isnt adding any, not even the first object
then either that code is not running or there are no objects with that tag in the scene at the time the method runs
i looked it up a recommendation i saw was to use AddRange(GameObject.FindGameObjectWithTag("Hero")); but when i do that, i get this compiler error is VS :
Error CS1503 Argument 1: cannot convert from 'UnityEngine.GameObject' to 'System.Collections.Generic.IEnumerable<UnityEngine.GameObject>' Assembly-CSharp C:\Users\nanak\My project\Assets\Scripts\Battle\BattleManager.cs 26 Active
AddRange() wants a group of objects, FindGameObject() returns only 1 object. Either use Add() or FindGameObjects(), with an S at the end
@pulsar lodge
would i want to run code capping my velocity in fixedupdate or update? It should be fixedupdate I think, just wanted to double check
why do you even need AddRange 🤔
Fixed
Adding these objects to a list to determine attack order (turn based JRPG)
yeah but you don't need add range but whatevs lol
and so that i can control their character states (dead, waiting, performing action, etc)
also GameObject type is as useful as watching grass grow
you should use something more specific
public List<Players> PlayersInBattle = new ();
🤷♂️
skip uneeded GetComponent()
Hello everyone, I'm super new to coding and Unity. How can I save the y-position of my gameObject in a new float var? I'm supposed to use that later for moving my character forwards/backwards. It's probably very easy to solve but everything online just confuses me, too much info for a noob 
float myFloat = gameObject.transform.position.y;
Can drop the gameObject part btw
transform directly accessible from any monobehaviour
float myFloat = transform.position.y;
that variable is only usable in the scope, the two brackets {} where it is declared, so you might want to declare it inside your class instead your method:
public class YourScript : MonoBehaviour
{
float myFloat;
void Start()
{
myFloat = transform.position.y;
}
}```
Note that what Gruhlum said is saving the VALUE, which is exactly what you want.
It won't change even as the transform changes position.
If you saved the transform of something, you are capturing a REFERENCE to the component, and whenever you get the y value of it, it will be the currect y position, and thus not really what you want
As you learn, telling the difference between a value and reference can be important, so I just wanted to put that out there.
Best of luck!
Thank you! When I try the solutions it always says "error CS0236: A field initializer cannot reference the non-static field, method, or property 'Component.transform'"
I think I tried what you shared already but something is lacking here xD
hello guys could someone help me out if i use colliders my character cant go through them but i want it to trigger example a door
thing is when i click on the trigger thing it just goes straight down
it sounds like you wrote float y = transform.position.y in the body of the class
which defines a float for the class (y), and tries to immediately assign a value to it (transform.position.y) as the class comes into existence
but you can’t do that because transform.position.y is not a compile time constant
why does triggers have a rigidbody then
door triggers should just be trigger colliders. No rigidbody needed
like, you can only do that second part if the machine knows exactly what to assign before any code is run
one gameobject needs a rigidbody to receive the collision/trigfer message
well like coins there are supposed to be floating mid air but i want them to trigger them another thing is door im turning off the sprite renderer when its gets trigered
ideally the object that goes in the triggers tho
coins can be triggers.
the door can be solid
but they are supposed to float in the air when i make it a trigger they fall down
because u have a rigidbody..
remove it
the coins?
dynamic rigidbodies have forces applied to them
sounds like they have rigidbody with gravity on they will fall
yes it should only be on player
i would give it a static rigidbody
Ah makes sense. I placed it somewhere else but my gameObject still won't move, I guess this would result in too many questions, thanks for helping people 
rigidbody lets it receive messages about collisions. But static means physics system needs not worry about moving it
sure
if player has rigidbody already no point in rigidbody on coins 🤷♂️
You should show the code you have now
depends on how you want to put it
if you want coins to detect player, or player detect coins
As nav said, the rigidbody only needs to be on one object, it will send the message to both colliders in the collision
And yeah, whichever one makes sense will work
have a static rigidbody on a coin doesn't make sense to me and probably a waste of rigidbody
both are valid
what are we looking at?
like i have the trigger on
that is the result
the key went straight down ignoring other collisions lmao
what is that script doing
I i thought static RBs are supposed to be essentially free?
at least physics2D basically assumes colliders with no rbs have a static rb
not sure, are they though?
if they are being included in the physics system for something besides a collider. Idk just seems like it would be more fit for maybe a static collider map with composite or something
you misspelled amplitude
doubt any of this was helping not fall in ground
you're forcing positions
= teleport
know that if you want the collider to move, you need to move a rigidbody
but im already using the first establish positions it had before hand
ok let me remove the script and let me see
and moving the transform will be kind of shittily trying to move the collider
dont use physics just to animate a coin /key lmao
use something like DoTween
and just reise the key and fix the min/max no reason a collider being trigger should prevent what u want
hahah ok
i would probably split it into 2 gameobjects, and move the transform of just one with the sprite.
I need to move the object by using "addforce()" and take the y position * transform.forward, maybe that's what I mess up? I'm lost
if you move the transform while it has a collider, you’ll get janky collision
^ also valid way
you want to move just the object with a spriterenderer
then you won’t fuck with collision/physics at all
although only animating the sprite object will cause bad trigger /collision for pickup
Why do you want the yPosition for forward movement?
You just want to use that movementVector you create in Update
mario does it like that. the hitbox of a coin is static, while the coin moves
I need to do it that way, I learned it in another way in the lecture but I think he wants to test or annoy us not sure:D
are there extra performance cost for using string overloads of GetKeys than the Keycode overloads?
if you do want the hitbox to move as it hovers, you absolutely need a kinematic rigidbody on that collider
in 2D , forward is positive X
in 3D, forward is positive Z
why?
That doesn't really make sense as a reason.
A lecturer said you need to do it with the y position?
Are you sure they weren't talking about the second addforce where you handle jumping?
(Even that doesn't really make sense honestly)
AddForce doesn't need to know the current position explicitly. It already knows the rigidbody position. It just needs the direction and magnitude (a vector)
what is the difference between kinectic and static?
it just doesnt make sense
otherwise you’re just teleporting the collider, and it’s coordinates won’t be synced properly
kinematic can only be moved with code, static doesnt move at all
Eh guess it depends, its farily ok in 3D to only animate transforms with collider
a static rigidbody is effectively the same as no rigidbody
unless , the "forward" in ur game is like raiden
never had a problem hitbox being that inaccurate
good old arcade game lol
static = never moves, kinematic = you tell it to go from point A to point B (ignoring all force). dynamic = you actually sovle forces and velocity vs positions of everything else
usually the animation/translation is too low to notice an impact
probably, but he should learn right, instead of learning it the wrong way, then going on to make the whole game on the premise of moving transforms
I couldnt imagine having a bunch of kinematic coins animated just to get a slight chance of precision
kinematic RBs aren’t really that expensive tbh
Yeah my object was moving before but not in the way I need to do it now, I guess it doesn't make sense
maybe I misunderstand, but it says (translated from German)
"Store the Y (forward/backward) component of this vector in a Member variable of type Float so you can access it from elsewhere.
Pass this float value in FixedUpdate() to the AddForce function Rigidbody further to make the car move forward and backward. About the direction to specify the acceleration, multiply the value by the transform.forward of the rigid body. Specify a suitable ForceMode"
i animate coins only for giving it much more awesome effects
ah my brain well im using velocty to move around but i heard that you should avoid using them because they consume alot of resources and whenever you can use trasform/translate
or just simply moving it around to annoy players lol
everything consumes resources , need velocity for rigidbody but moving kinematic MovePosition, is fine too. just dont use translate for collisions
you shouldn't worry about that stuff rn
just make it work correct
but thats moving, not animating tho
dynamic means you’re actually making everything receive forces from everything else, and all the dynamics get solved at once.
kinematic means it goes directly to where you say, and it doesn’t check for anything stopping it
but using an RB to move will keep colliders synced
example: if collider ceneter is at y=0; then i set transform.position.y =5f; do you know where the collider’s center is now?
it’s not at 5f. it’s still at 0f
oh ok i gotchu
so if any of your other code is reading stuff, it will all be messed up
but if you set rigidbody.position.y = 5f, now the collider’s center actually is at 5f
ok i understand so basically even if the gameobject is all the way into the ground the collider is still in the same place so that is why it needs a rigidbody to follow it
the rigidbody doesn't follow anything
and you shouldn’t set position like that normally. you would want to use rigidbody.MovePosition, but the point still stands
it controls the transform, if you are using transform directly it defeats the whole purpose of a rigidbody
rigidbody and transform write to each other
colliders live in rigidbody space. the collider will only actually move when the rigidbody’s position is moved.
and if you set transform, that won’t happen until the next time SyncTransforms is called
which it is called automatically at physics similation
yeah colliders are part of physics
but if you calculate some numbers based on some numbers, thinking everything is synced and gucci, moving the transform while you have a collider can fuck it up
Oh i see my code is super fuck
i added the rb now the collider follows the movement
but it goes to the ground thing im kind of dumb with programming basically i made my code always deliver between 1 to -1 so the y axis is always going there
what?
why does you key have a rigidbody ?
didnt you guys told me to add a kinectic rb to my object?^
is there any chances to not force it?
why dont u show us what it looks like in game view
yes you're not moving local position
you're starting your y at 0.5 world pos
and then 0 and so forth
sorry 0.83
cause thats what you have in inspector
using JetBrains.Annotations;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
public class BallBehaviour : MonoBehaviour
{
private Rigidbody2D rb;
float force = 20f;
public Vector2 addition = new Vector2(1, 1);
Vector2 speed;
Vector2 constantspeed= new Vector2(30,30);
void Start()
{
rb = GetComponent<Rigidbody2D>();
Vector2 randomdirection = Random.insideUnitCircle.normalized;
speed = randomdirection * force * Time.deltaTime;
rb.AddForce(speed,ForceMode2D.Impulse);
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.CompareTag("player"))
constantspeed += addition;
}
void Update()
{
rb.AddForce(speed);
}
}
why does the ball break through the bars and the barriers?
they are all rigidbody, doesn't rigidbody add an hitbox?
you shouldn't be adding force inside of Update like that. and you also shouldn't be multiplying your force by deltaTime
also !code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i mean just a small animation is fine? the key???
if i don't it stops after a certain amount of time
it literally just need an animation, and a dynamic RB with gravity disabled to be a pickup object
then do it in FixedUpdate or just assign its velocity
otherwise your object will just increase speed indefinitely and that speed will be dependent on the framerate
u need to use a root motion tho @nimble blaze
time.deltatime fixes the speed so that it is not dependent on the framerate
lol not the way you are using it
wait lemme show u
if you add a rigidbody, in the code, you want to call rigidbody.MovePosition
real quick
how do i make his velocity so that it doesn't slow?
why?
make sure the rigidbody has no drag and the physics material has no friction. then just assign its velocity
i solved my code
because you only multiply by deltaTime once when you create your variable. so not only are you not accounting for variances in deltaTime each time you apply force, but you are also just continuously adding force every single frame
yes
still not right
aight
i did it with code
you want to do Rigidbody2D rb;
rb = GetComponent<Rigidbody2D>();
and then rb.MovePosition
ofc rb can do it
instead of transform.position
yup
moving transform moves the sprite, while not moving the hitbox properly
this is good for if you want the hitbox to be non-moving
but not if you want the hitbox to move along with the sprite
do you understand?
you need MovePosition with kinematic
it will move out of sync
meaning any code that depends on it later will be using wrong numbers
eg it will look perfect now, but potentially break later
https://paste.ofcode.org/CEqbwNQWWyqnLANQERgb8B
is this fine @slender nymph ?
well now you're just going to make it go in a specific direction no matter what because you've hard coded the velocity. but it's better than it was.
oh and you're still unnecessarily adding force in Start
now go add colliders to your objects because no, Rigidbodies are not colliders
velocity += addition; 🤔
i want to add some speed every time the ball hits the player
i recommend watching a tutorial for how to do this. because it looks like it is supposed to be pong and there are dozens, if not hundreds, of tutorials for making pong
yeah it is
ig but you dont need a whole variable for only Vector2.one
i didn't know Vector2.one existed lol
yeah pong has many diff movement types, I did something for Breakout classic type Bat/Ball
I also used velocity but collision I dont use physics because Physics Materials suck
too unreliable
Instantiate(_wallFBO, new Vector3(_player.transform.position.x, _player.transform.position.y, 0), Quaternion.identity);
_camera.Follow = null;```
Any ideas why ?
@nimble blaze hey can u check this out, maybe this is what u want?
i mean as long as it works as u want, any solution should be acceptable
what is the first screenshot of I dont understand whats happening here
basically i use that cs Instantiate(_wallFBO, new Vector3(_player.transform.position.x, _player.transform.position.y, 0), Quaternion.identity);
and it doesnt spawn above the player it spawn in a wrong position
if this is what u want then u dont even need rb at first place
its possible your pivot is not where you think it was
see?
yeah ur in center mode
oh, it cant be in center mode? i thought that would need to be in center mode
so ur not seeing the true pivot
ok got it thank you 😄
pivot and center is totally different thing
how can I move the pivot to the place i want without moving the object?
its an empty objkect
that is parent of 4 child 2d sprites
you have to match the children
unparent it, move it proper
then reparent
pivotting is just about parenting
now if I stand still it works.. if I am moving with the player it appear a bit off.. is there a way to fix that? or as it is updating the player position there is no way to do it?
- make sure ur in pivot mode
- create an ampty object
- put all the objects u want under it
feeling very stupid right now, does anyone know why my camera is turning unevenly?
when u rotate the parent, it acts like pivot and rotate the rest
first configure your !ide. It is a requirement of this server
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
also when I make my camera to stop following me its like I lost a lot of movement speed with my player.. wierd.. and if I stand still it works.. if I am moving with the player it appear a bit off.. is there a way to fix that? or as it is updating the player position there is no way to do it?
if I stand still it spawns on the correct place
if I am moving right it spawns where u see now
which one is which
If I move left itt spawns more to the left.. and also i turn my camera OFF to follow me and my player I dont know lose a lot of movement speed
the walls
the idea is... i will be playing. when i reach lvl 30 the final boss appears.. but now the camera needs to stop following me and I will be trapped inside those walls
Hello, could someone take fast look at my lighting question said in that channel? I say it here because almost no one watches it... 🤷♂️
#archived-lighting message
the player movement actually is the same .. it was just an impression.. but the walls appear slightly to the left or right depend which direction I am moving.. is there a way to fix that? I am saying to spawn on my location but it seems the movement of the player is influencing it a bit
Is this 2d? And forward is Up?
If so, I guess I get it.
It's not 2D and forward is not up, I want to get this but I can't figure out 
Then.... that doesn't really make sense 😂
The y value would NOT be forward or backward. It is sounding like Z would be forward and backward (which is how most 3d is, unless doing faux 2d, in which x would often be forward backward)
I feel like just using transform.forward makes more sense that the yValue variable you made.
Maybe ask the professor for clarification?
ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
System.Collections.Generic.List`1[T].get_Item (System.Int32 index) (at <4a4789deb75f446a81a24a1a00bdd3f9>:0)
StormController.Update () (at Assets/StormController.cs:101)
i got this error
show the StormController class
you understand what the error message says?
Indexes start at 0, so you have to consider that.
Also, the list might be empty
I wondered too, I managed to make it move to the left and right side tho, but yeah Idk how to solve this task. its the 3rd homework, it's only going to get worse
yes it asking for not negitve value
not only
That is not what the error is saying (well, it does, but I bet that isn't the issue)
Index was out of range. Must be non-negative and less than the size of the collection.
Index was out of range.
Index is the position you are trying to access
range is the size in elements of the array/list/collection you are trying to access
it has a range, an array with length 5 will have a range 0-4
error says you are trying to get something that is beyond the range of valid positions in the collection
"Your ShrinkCircle method seems correct for its purpose, but there is an issue in the way you're accessing CloseTimes in the Update method. The error you are facing (ArgumentOutOfRangeException) indicates that you're trying to access an index in the CloseTimes list that doesn't exist.
Here's the problematic part:
csharp
Copy code
if (((int)timeElasped) > CloseTimes[closeTimesIndex]) {
// ...
if ((int)timeElasped - (int)timeElasped != CountDown) {
CountDown = Mathf.Clamp(CloseTimes[closeTimesIndex] - (int)timeElasped, 1, 1000);
// ...
}
// ...
}
You should perform additional checks before accessing the CloseTimes list to ensure that closeTimesIndex is within a valid range. You can use the Count property of the list to check its length. Modify the code as follows:
csharp
Copy code
if (closeTimesIndex >= 0 && closeTimesIndex < CloseTimes.Count && (int)timeElasped > CloseTimes[closeTimesIndex]) {
// ...
if ((int)timeElasped - (int)timeElasped != CountDown) {
CountDown = Mathf.Clamp(CloseTimes[closeTimesIndex] - (int)timeElasped, 1, 1000);
// ...
}" this chatgpt said
Where do you get closeTimesIndex?
And yeah, checking that it is less than (but not equal to) count is good
typical GPT, 'fixes' your error without actually solving the root cause
what would be more efficient?
Use collision to detect an object's tag or make a variable for that object and then use collision to detect the GameObject?
Use whatever is easier to keep organised for you
how many collisions you expect per frame?
most efficient is direct reference comparison
so the variable
tell me how many you expect
like one every couple of seconds
then it doesnt matter
it will matter when you will have 10k collisions per frame, where string/tag/GetComponent will have actual effect
i mean, it's a phone game, even then it doesn't matter?
even then, once every couple seconds
alright thanks
differences there are in microseconds
can we simulate a button press via code?
Hello,
I'm having trouble intuitively understanding how GameObjects work, or just objects in general
If I have a class called Cell, not inheriting from monobehaviour
{
public GameObject cellObject;
}```
and a class that makes an array of them
```public class NewGrid : MonoBehaviour
{
Cell[,] cellgridArray = new Cell[10, 10];
}
Why doesn't this actually instantiate gameobjects? I know you can iterate through and instantiate them, but I don't understand why that's necessary
Doesn't making an array of Cell objects necessarily make their gameobjects?
with new input system probably, with old, you have to have a wrapper
wrapper?
class is what c# calls a reference type, the array of class Cell and class AnythingElse has equal size of element - the size of a reference, a 64 bit integer
anything inheriting an object, so a class has to be allocated manually through new or Activator.CreateInstance
because what happens is you create that object on the heap and a reference to it is returned to you
structures are value types and they behave like you expected
they are stored by value, embedded into the object they are stored in, so an array of Vector2 will have element size of 2 floats
and will be created in place when you allocate the array
yes any wrapper, input system layer, anything on top of unity old Input
so that you dont directly use Input.GetKey
but instead you do that through a layer
bool pressed = myInputLayer.GetKey(..)
then the layer can "simulate" key press
I'm trying to be able to select an AxisFramePrefab in Unity it & move it. An axisFrame prefab is basically 3 small cylinders looking like x,y,z axis. So If I click & drag on Y cylinder, I should be able to move it in Y-axis only & vice versa for other cylinders. But there is no smooth movement. Can anyone tell me what wrong I am doing?
use Plane struct
instead of initial offset, create initial plane in which you will operate
then you can raycast that plane instead, not relying on hitting any collider
let me try. thanks for suggestion
Are CodeMonkey's code practices good? I'm watching one of his YT tutorials and I wanna make sure I'm learning correctly before I step in too far, the vid is pretty popular and big in views so I assume you guys know a bit about CodeMonkey
So I'm trying to pass an input from InputField into my CheckString function however it is returning null. For some reason my input = s goes null once I hit enter... any thoughts?
Here is the setup:
public void ReadString(string s)
{
input = s;
// This checks to see if the string written is the same being read
CheckString(currentWord, input);
}
And CheckString method for reference:
private void CheckString(string read, string write)
{
Debug.Log("read: " + read);
Debug.Log("write: " + write);
if (read == write )
{
Debug.Log("Read equals write");
}
}
The first read is okay, it holds the value as expected but once I press enter it changes to null
hmm when i change it to submit I still get the same error
seems a way to mitigate it is to bypass the callback and just read the value on input
wdym bypass the callback?
just one
when i press enter it calls the function
but the read variable disappears upon submit
same with write on the next submit
the form seems to "clear" the value
everytime i hit enter
try disabling navigation on the component, anything changes?
how do i do that?
in the inspector navigation dropdown
no dice
im not sure whats going on there, you can try googling, or if you know how to use the debugger, you can copy the ugui package into the project which will allow you to navigate the call stack and find where it loses the reference
Is there a way to rotate the camera with clamp using Input.GetAxisRaw? I notice alot of guides store the values rather than use it per frame. The reason I ask is because I want to incorporate a recoil variable in adition to applying the input
Yeah I'll do that
Hey guys.. I created an object and when I instantiate it on the players location, if I am standing still the boss spawns at the correct location, but if I am moving to the right it spawns like a bit to the right etc.. also for the left and so on.. any fix?
Whatever is happening is due to your code. The fix will be to change the code. Can't say more without seeing the code.
You also need to explain what you want to actually happen (what is the correct behavior?)
true, I am using this as the player movement. ```cs
private void PlayerMovement(){
float horizontalInput = Input.GetAxisRaw("Horizontal");
float verticalInput = Input.GetAxisRaw("Vertical");
transform.Translate(Vector3.right * playerSpeed * horizontalInput * Time.deltaTime);
transform.Translate(Vector3.up * playerSpeed * verticalInput * Time.deltaTime);
}``` When I spawn the boss like that: ```cs
private void InvokeFinalBO(){
Instantiate(_finalBossOne, new Vector3(_player.transform.position.x, _player.transform.position.y + 21.4f, 0), Quaternion.identity);
//Instantiate(_wallFBO, new Vector3(_player.transform.position.x, _player.transform.position.y, 0), Quaternion.identity);
_camera.Follow = null;
}``` it should spawn on player position. itworks BUT if I am moving to any place.. it spawns a bit like 1..2..3..4. units to the direction I am going..
it will spawn at exactly:
new Vector3(_player.transform.position.x, _player.transform.position.y + 21.4f, 0
The speed your player is moving is irrelevant
but it doesnt.. and if it does.. it mess up.. because the boss just move left when reach end of the screen he moves to the right.. just that.. but if I am moving with the player as he spawns not where I want he goes beyound the screen 1..2..3...4 units
if am standing still it works as intended and he moves to the left or right until the end of the screen and doest go further away.. so might have some frames of something that is messing with it.. dont know how to fix.. maybe say that if the player is going to the left.. spawn him a bit to the right etc
You'd have to show the code for the boss etc. and also possibly video or screenshot of the scene and what's happening
What I do know is that Instantiate spawns objects exactly where you tell it to
ok thank you
float noiseHeight = Mathf.PerlinNoise((float)(x/ height), (float)(z/width));
Assuming this line of code is in for loops that change the x AND they y values. Why am I getting 0.4652731 regardless of the value of x or y?
Ive seen people suggesting that using ints instead for floats might be the issue, but it doesn't seem to be making much of a difference whatsoever
Perlin noise is always teh same value at integer boundaries
I.e. you are plugging in (0, 0), (1, 0), (2, 0) etc
you need to sample the noise function between those values
You're sampling at the dots and you need to sample between the dots
Also x/ height < if x and height are integers, this will do integer division
casting to float AFTER that is useless
You have: (float)(x/ height)
You need: (float)x/height or x / (float)height
Okay gotcha, I was about to lose my mind lol
im confused on why the objects that are hit by the ray and stored in the hitThing RaycastHit variable are only added to the lockedOn list once
{
camPos = mainCam.transform.position;
if (Input.GetKey(KeyCode.Mouse1))
{
RayOut();
lockedOn.Add(hitThing.transform.gameObject);
hasLockedOn = true;
Debug.DrawRay(camPos, mainCam.transform.forward * 100, Color.magenta, 3f);
}
if (Input.GetKeyUp(KeyCode.Mouse1) && hasLockedOn)
{
Destroy(lockedOn[lockedOn.Count - 1]);
lockedOn.Clear();
hasLockedOn = false;
}
}```
That's not enough info to answer your question
what else do you need?
Share the whole code
!code
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
the ray is being cast every frame, which means that the data stored in hitThing should also be updated every frame. So in that sense, hitThing should also be added to the list every frame, even if its the same data right?
should i maybe use a while loop instead and just break when the player stops pressing the right mouse button?
What’s the goal? Currently all the code should be doing is destroying 1 object (the last one you laser-ed)
the goal is to add every object that the raycast has hit during the time mouse2 was held down, and after mouse2 has been let go, to destroy every object in the list according to the order it was added
how come hitThing isn't being added to the list every frame?
what makes you think it's only being added once?
Also why do you need a list in the first place?
i guess because it only destroys the last object that was hovered over
Destroy(lockedOn[lockedOn.Count - 1]);
lockedOn.Clear();```
this doesn't require a list
- Check your console for errors.
because your code is literally doing that
read it
right here #💻┃code-beginner message
notice how you are only calling Destroy one time? Only one thing is going to be destroyed, and that thing is the last element in the list.
Because that's the code you wrote
Destroy(lockedOn[lockedOn.Count - 1]);
"Destroy the thing at the last index in the list"
huh
What are you confused about
lockedOn[lockedOn.Count - 1] < this gets the last element in the list
Destroy destroys whatever you pass into it
doesn't .Count mean all of it?
what?
Count is just the number of elements in the list
COunt - 1 is the last valid index in the list
oh i see
Therefore lockedOn[lockedOn.Count - 1] gets the last item in the list
there's no magic that will make Destroy suddenly destroy multiple objects when only being called one time
no i know
You should:
- Use a HashSet instead of a List, since it doesn't allow duplicates
- use a
foreachloop to loop over them all and destroy all of them
aw man
i was gonna use a hashset at first but i thought it wasn't the right type for this kind of thing
Why?
i dont know much about hash sets but i thought it kept less information, or maybe didn't keep an ordered list
i do
Ok then just only add a thing to the list when it's a new thing
When you destroy them, it instantly destroys them meaning the order doesn’t really matter. You can use a hashset which makes sure you only add unique game objects to the list (that way you don’t add like 100x the same game object).
What do you need the order for though?
If you want to play an animation so they destroy in order, you should use a hashset and a list. Use the hashset to verify you are adding a new game object, and use the list to destroy them in order
the destroy part was just for functionality right now, i was going to make it so an object zips between each object in the list and destroys them along the way
Hashset might not work very well with the hit struct.
It won't
they should be storing Collider or GameObject
they should not be using the RaycastHit struct so widely
lockedOn.Add(hitThing.transform.gameObject);
this should fix that though right?
so yeah something like:
HashSet<GameObject> uniqueObjects = new();
List<GameObject> objects = new();
void Update() {
if (Input.GetKey(...)
&& Physics.Raycast(... out RaycastHit hit, ...)
&& uniqeObjects.Add(hit.collider.gameObject)) {
objects.Add(hit.collider.gameObject);
}
}
}``` basically
and then Clear() them both when you let go of the button
hmm alright
{
Move();
}
private void Move()
{
Vector2 moveInput = input.Move.normalized;
Vector3 move = transform.right * moveInput.x + transform.forward * moveInput.y;
transform.position += move * Time.deltaTime;
animator.SetFloat("horizontal", moveInput.x);
animator.SetFloat("vertical", moveInput.y);
Debug.Log("Im Moving");
}``` im trying to get my charcter to move with the new input system , but its not moing when pressing the keys, can anyone see what im doing wrong. in the code
Where is input.Move.normalized coming from?
The code you shared doesn't explain how you're handling input at all
For System.Index and System.Range, all you need to do is polyfill them. You can do that manually or you can use a package like IndexRange for it.
- Download package (button on the right)
- Open the .nupkg in an archival program (it's just a ZIP file)
- Go into
lib/netstandard2.0/(ornetstandard2.1for Unity 2021.3+) and copyIndexRange.dllinto your project
void Awake()
{
playerActions = new GameInputActions();
playerActions.Enable();
}
private void OnDisable()
{
playerActions?.Disable();
}
public Vector2 Move => playerActions.PlayerActionMap.Movement.ReadValue<Vector2>();``` here is what is handling my input.
See here for a list of stuff that works when polyfilled: https://github.com/DaZombieKiller/UnityRoslynUpdater#language-support
Where did you get the input reference from? Is it referencing an object in the scene? Or perhaps a prefab?
i have two scripts player input and player controller , the first code is from my player controller and the one i shared is from my playerInput. public PlayerInput input { get; private set; } is the input.
that's just the property declaration
how is the property assigned?
(btw PlayerInput is not a good name for that script, since there's a PlayerInput component in the input system package already, which is confusing)
input = GetComponent<PlayerInput>(); i assigned in the start function of my PlayerController.cs, the PlayerInput.cs script is on the player object in the scene. i hope Im making sense.
Ok can you do Debug.Log($"Move input is: {moveInput}"); in your PlayerMovement script then, just to double check we're not actually getting any input?
Move input is: (0.00, 0.00)
UnityEngine.Debug:Log (object)
PlayerController:Move () (at Assets/Scripts/Player/PlayerController.cs:46)
PlayerController:Update () (at Assets/Scripts/Player/PlayerController.cs:31)
here is the debug, im stuck at 0,0,0 .
Can you show how you configured the action in the actions asset?
Hmm is there a reason you have those prefab overrides?
its a prefab
This isn't a prefab
This is an instance of a prefab
And those components are only on this instance, not on the prefab itself. Hence the overrides (in blue, with plus signs)
Say I have an object that has bool isLookingForAFight = true. I want the object to move toward and collide with another object with the same var value. How do I do that? FindGameObjectsWithTag is similar to what I'm looking for, but instead of looking for a certain tag I want the object to look for a certain variable
Rather than setting some bool on a script, you should add all of the NPCs that are looking for a fight to some list on some central manager script
Then simply check what's in that list as needed
It's a bit too advanced for me, lol, but I'm gonna try it nonetheless. Thanks
!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.
yep my code is here, Here is the url version of it
i think unity hates me
why
every time i try to type any of my code it never works even if i copy someone elses
Well let us see the code
ight hol up
help me i still got errors after have chat gpt help me with me code
This is a download link for mobile
You should do it as the bot suggested
so these are my 2 scripts how do i add a double jump to them
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public CharacterController2D controller;
public float runSpeed = 40f;
float horizontalMove = 0f;
bool jump = false;
bool crouch = false;
// Update is called once per frame
void Update()
{
horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed;
if (Input.GetButtonDown("Jump"))
{
jump = true;
}
if (Input.GetButtonDown("Crouch"))
{
crouch = true;
}
else if (Input.GetButtonUp("Crouch"))
{
crouch = false;
}
}
void FixedUpdate()
{
// Move our character
controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump);
jump = false;
}
}
the second one has to be a file
!code
Use a paste site
📃 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.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
thats the second one
new input system backend was'nt enable ,
updated version https://hastebin.com/share/adeledisib.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
was going to ask that but thought you would have gotten an error in that case.
hi im making a tower defense game and whenever i place a character i get the error: UnityException: Transform child out of bounds
MouseHoverScript.Update () (at Assets/Scripts/MouseHoverSelect.cs:97) and when i place a bunch of characters after a few seconds i get the error: NullReferenceException: Object reference not set to an instance of an object
MouseHoverScript.Update () (at Assets/Scripts/MouseHoverSelect.cs:93)
heres the code:
https://hastebin.com/share/ofireqineq.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
This is empty. Maybe forgot to hit save?
its telling you hit.transform.GetChild(0).position; is out of bounds then you have hit.transform that has no children
ye but it has children thats why im confused
hello! when I use input field, the text (the value that is written in the field) is by default a TMP UGUI right? I need to target that in UVS, but due to a problem, I cant be using Get Text of TMP UGUI, I need to specifically target only a 'TMP text' to get its value, can I turn the value of that input field to TMP text instead of UGUI without messing up anything ?
What?
What is UVS?
well the computer says otherwise
i trust the computer
idk it has children
visual scripting
The error says it does not.
Do Debug.Log($"getting child from {hit.gameObject}", gameObject);
It will show that it is not the object you expect
Wdym by "can I turn the value of that input field to TMP text"?
then its not hitting what you think it is..
and there shrinking storm using an force flied from 2018 in spainish
You shouldn't be referencing that thing directly anyway
just read it through the TMP_InputField
SOunds like a fake problem / XY problem
just thank microsoft for their beautiful creations
anyway your variable is of type TextMeshPro
TMP_Text is the parent class of both TextMeshPro and TextMeshProUGUI
just use TMP_Text
I don't understand this comment
what does Microsoft have to do with the type of your variable in your script
thats the part where i said, 'due to a problem', Im using something called 'Microsoft mesh', and its basically not allowing 90% of normal methods that are in UVS
i fixed the error now, i just need to refix function tho lol. thx
I can't imagine any scenario where TextMeshPro would be available but not TMP_Text or TextMeshProUGUI. In fact TMP_Text is the parent class for TextMeshPro so it's not really possible for the former to not exist when the latter does
I would guess you are doing something incorrectly
well, it is in my case, not much that I can do to that
I'm hitting the doubt button on that
It is a parent class.
It is objectively not possible what you are saying
TextMeshProUGUI inherits from TMP_Text..
Meaning TextMeshProUGUI IS TMP_Text plus some extra
I think you just picked the wrong type in this dropdown
Maybe just write a regular C# script
not possible
cant be compiled by microsoft mesh
trust me ive tried
ok well idk then, stop using that shitty product
not my choice
maybe try legacy input field?
Then what you want to do is not possible
once again
Wdym by "compiled by Microsoft mesh". From Google it sounds like it's just a VR library.
sigh
yep, same thing
idea is, click on a cube (note), and have the text from the input field be in the text that s on top of the cube, simple enough.. yeeeaaahhh..
if anyone could suggest another way of doing it, to have a similar system to 'sticky notes', id be grateful
Looks like Mesh has its own UI stuff like this dialog?
Maybe you should try to use those?
Looks like there's some other concept called "Cloud Scripting"?
Seems to mention TMP components as being supported
idk if that helps
anyone know how i can add a doulbe jump to my script
Make an int called jumpQuota or something. Set it to 2
When you jump, subtract one.
If it's 0, don't allow jumping.
In your ground check, set it back to 2
how do i call a variable from one script to another
The same way you do it with built in Unity components.
- Get a reference
- do whatever you want with it
how do i reference it
anyone know why i cant start my thing
If you can't, it means you're probably instantiating the object? You have to pass the reference returned by the Instantiate call somehow
i hit play and nothing happens
It really depends.
What is your "thing"? Just EVERYTHING? Show a video
You are clicking start so fast nothing COULD happen.
Click it ONCE
clicking it once doesnt do anything
Do you have a rigidbody with gravity enabled?
yeah
Show a video where you only click it once, and show more of the inspector if possible
that's a lot of errors
You have 65 compile errors
Can't play with compile errors
i didnt see that they where unchecked lol never noticed thenm
fixed it
now i have the problem of it never resetting the jumpcounter
Every fixed update you seem to set m_Grounded to false and use wasGrounded.
Ah, I see where you set it true
fix your errors before compiling code
it works thanks
Seems like your !ide is not configured btw
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
it keeps unconfiguring
also anyone know why i get this
does anyone here know how to snap assets on the axis and transform them at a certain increment on the 2D URP
click the Axes and let your ancestors guide you 😄
can i add a imput there
https://docs.unity3d.com/Manual/class-InputManager.html here's are the keys you can add
where do i say what key it uses
and what would i say for control
would i say ctrl or control or Ctrl or Control
it just keeps removing it
Look at the "Mapping virtual axes to controls" section here https://docs.unity3d.com/Manual/class-InputManager.html
thanks
Is there a (simple) way to rotate a vector by an amount in radians
quaternion.eulerAngle() uses degrees but most of the trig functions return radians, I can convert easily enough but I'm curious
Mathf.deg2rad and mathf.rad2deg
The simple way is to convert
i have doubt about the node system that
i am working on tiger and goat game and the game consist a kill condition for tiger to kill goat
but the condition is tiger should actually kill the goat if the goat is there infront of tiger and skip that node and transform its position to the next node
can some one help me with this
i am not able to get the logic
how are you storing the data for these nodes? is this like a graph or just array/2d array?
There must be some definition of what "infront" is, like with arrays it would be based on index
i am storing the data of each node in the list as each node has the node script on it and just manually giving each node that how tiger will move
Adjacency list
So you have defined next node already
yeah
so every node has its specific list of elements on which tiger can move
and the kill condition list which is neighbouringnextnode list is having thenodes on which tiger if the tiger will come then it will have this nodes to move
how to use animator if your main model(mesh) is child object of an empty game object?? can we still animate the character ?
the player mesh is child object of playerholder empty game object and i want to animate the player for idle and running animation , how do i do it?
What are the purposes of having neighbouring nodes? (Not next node)
I think you mean: for each node: it checks its neighbours next nodes to see if there is tiger on the next node, and further check will the tiger comes(?) to itself (the node that are checking), then assign its position to tiger s position
you should have the list ordered in a certain way, or define each node like
public Node left, right, forward, back. If its random (just based on how you decide to drag the transforms in) then your only check for direction relies on the position which might be annoying.
Im not sure what neighbouring next node is for though in your component
this is a code channel
oh sorry about that.
yes
I prefer the tigers done the checking, for each neighbouring node (not the next node) of the node that the tiger on, check if is there any goat in the neighbouring nodes, and the next problem is to define direction, considering what bawsi said
One node may have multiples “next nodes” that tiger can jump into
we took a list and are storing the neighbouring nodes into the node list like this.
[SerializeField] private List<Transform> neighbouringNodes;
[SerializeField] private List<Transform> neighbouringNextNodes;
public List<Transform> GetNeighbouringNodes()
{
return neighbouringNodes;
}
public List<Transform> GetNeighbouringNextNodes()
{
return neighbouringNextNodes;
}```
How to check if a goat is on the node? collision?
The tf should be assigned in a Ordered Way, not related to how you stored the tf (using array or list or multiple variables)
What is the “Occupied by goat” field….
ohh that was just an experiment the code does not have related to it just ignore it
i understand already that they are lists, but what is neighbouring next nodes actually for?
you should store the reference to Node instead of transform
Are the positions of tigers/ goats are limited( they can only stay on the nodes)? Though this is unimportant, consider assigning corresponding node by the animals’ position to animals
so actually that is to check for a movement when the tiger will kill the goat and it will skip one position and move to the other
The node can reference to tigers/goats and vice verse
yes they can only stay on nodes
yea thats not needed then, it should just check through the neighbouring nodes
ummmm okkk
i am not getting that how will i check if the node is occupied
Read what i have typed…
and one more thing is every node tiger and goat has different script on it for movement and there respective work then how should i write a kill condition for tiger
Instead of storing neighboring nodes as transforms, store them as Nodes, so that you can access it's members.
Then you can check if a neighboring node has a sheep or a tiger and what other nodes it's connected to.
ok ok
temporary variables used inside cycle, should i declare them before cycle or inside of it, if i don't need them outside of cycle?
i mean it will reallocate memory every time or something
what kiind of variables are you talking about? Primitives, Value Types, Reference Types?
reference types
Reference types are better declared outside of the method if that method is called many times
ok, thank you!
It's fine unless they are instantiated/created inside the loop
I will declare them inside the scope, since they are not needed outside the scope and the registers/stack/cache should be released
whats the different between SmoothDamp and lerp?
my game has 100+ UI buttons, i want to make it so that an audio source plays when any of them is clicked, excluding 2-3 buttons. Is there any way i can do this via code without having to assign each button manually, but instead i only assign the exceptions
like this?
I wouldnt use FindObjectsOfType incase you want to add new buttons in the future that dont play a sound. Everytime you'll have to remember to adjust this list, and having to remember previous scripts is truly a headache. I think it's worth it just mass selecting all the relevant gameobjects and dragging them into some inspector slot for which play a sound
selecting all the buttons is gonna take too long, and im surely gonna miss some, i know cause thats what i was doing until now
You can drag multiple items at once, and select multiple at once in the hierarchy
im well aware. Each button is a child of another object, and there are 100+ buttons
Not on pc but I think you can filter out all the irrelevant objects with searching
t:Button
I forgot if that displays parent objects
what's wrong?
public class SceneLoader : MonoBehaviour
{
public GameObject loaderUi;
Are the script using UnityEngine;
missing using UnityEngine;
is there really no way to automate this? cause each time i make a new button, adding that in the inspector is gonna be bothersome too
Why not just make a custom script and attach it to the buttons to let them add themselves to the list on Start()
Or Awake() or whatever
🤷♂️what you had above could work if you're really confident you'll remember to add to the excluded list everytime you need to. It's a lot easier to debug that you need to add a button to the list instead of "why is my button making noise when it has no scripts on it" 3 months down the line
either via event or singleton
That won't be a problem. But what i had above is not doing anything AT ALL.
Did u debug to see which part specifically isnt working? Now that I look at it more closely, it doesnt make a whole lot of sense to add a listener to every button that checks if its excluded. You should check if its excluded then add a listener if it isnt.
i think i found the issue, its only adding the sound to the 2 buttons which are enabled at the start of the game, and ignoring all those that get enabled after
how to get 2D object direction?
got vector for movement but idk how to convert it into angle
how do i make a 3d bird player controller
ty
for anyone whos experienced in UVS (bolt) here, what are the "methods" to create a cube + have it in a set Position + change its color ?
Hey guys.. I am trying to do something that might be simple but it seems that my mind cant figure this out with coroutines or invokingRepeating. Basically I have a boss that should shoot for 10 sec 1 type of bullet and after 10sec it stops and start shooting another bullet for 3 sec, and that repeats for ever.. tried with booleans, ifs, coroutines or invokes but 1 - or I crash the program with loops and whiles or it just doesnt work. any tips?
Show current code
"different types" of bullets should be a function or another prefab, it depends on how u do it
crash is not freeze...
10 sec shooting->10 sec cool down->3 seconds shooting->cool down
^ |
|-----------------------------<------------------------------------|
now you have a loop that can run on coroutine
oh, ok will try, thank you guys
keep in mind that coroutine waits will be affected by frame time, it will have a 0.01-0.03second delay (if ur fps around 60)
buuuuut switching should be fine, if not shooting bullets
yeah, its simple task but for me as noob is taking more than it should.. still getting around coroutines etc..
for actions that is extremely frequent , like 400RPM+ , do a simple timer
for action that is few second once or even 1-2 seconds once, feel free to use coroutines
so because i put movementDirection.x and movementDirection.y into the directionangle and movementDirection is controller by vertical and horizontal input
which set the direction angle vector to 0,0 when im not moving so when im using directionangle to rotate the character it keep rotate back to (0,0) rotation.
how to fix?
maybe not using the movementDirection.x and y but idk what value to put inthere to get the current direction
simply don't rotate when both horizontal and vetical are 0
ah..... lol thank
hey guys when I mouse hover a method that yes is not complete, it says +3 overloads for example.. how can I see the other overloads?
Some videos I see people clicking on an arrow, but mine doesnt have it so normally i crtl click on the method and go to the method class to check it but is there another way ?
done it like that and worked ```cs
private IEnumerator Shoot(){
while (true)
{
StartCoroutine(ShootNormal(10));
yield return new WaitForSeconds(10f);
StopCoroutine("ShootNormal");
StartCoroutine(ShootFast(3));
yield return new WaitForSeconds(3f);
StopCoroutine("ShootFast");
}
}
private IEnumerator ShootNormal(float duration)
{
float startTime = Time.time;
while (Time.time - startTime < duration)
{
Attack();
yield return new WaitForSeconds(0.5f);
}
}
private IEnumerator ShootFast(float duration)
{
float startTime = Time.time;
while (Time.time - startTime < duration)
{
AttackFast();
yield return new WaitForSeconds(0.03f);
}
} ```
If your ide is configured properly, it should show you the overloads.
prob it is not, as I cant see them, it just says it contains +3 overloads.. so now I always need to Control Click to open the class and check. But I have followed the steps here to implement everytihng on my Ide but I might have missed something tho. Ok thank you
You can scroll the overloads when entering the parameters(inside the parenthesis) with up/down keys.
what will u guys do to group up a set of poker? or make it into a collection
like dividing diamond heart spade and A-K
Hello, how can i create a turn system in my game. is it necessary to use enums?
dictionary<int,int>```
where 0,1,2,3 is code for diamond, heart, spade....
or
```cs
dictionary<enum,int>```
where enum can be diamond heart spade
i think enum int should be better
ty lol
yeah mine doesnt have that.
What ide are you using? Take a screenshot of what it looks like.
Visual Studio Code
You can scroll the overloads while you're typing .. I dunno if you can do it once you stop and leave it with an error, like in this screenshot
Hmm cant anyways. but all good thank you !!
I have a AnimationController and FBX animations, can I use C# to add these animations to the AnimationController?
Death movement overwritten
neither, I'd make a class named 'Card' and give it a field for Suit and Value. Then I put them in a List
https://gyazo.com/eaacaf53045e26f128b7a61b79ed9f96.gif
Hey, I would like to try to change the rotation locally as the bottom part is a child, but it starts moving relative to the whole object. Is there any way to change the rotation locally?
My goal is to try to move the bottom part whilst moving and the top whilst looking at the mouse
ahh...
show current code
Anyone knew how to make it so the camera can't moving around despite I put 'Time.timeScale = 1;' on the InventoryManager script?
also that ^
myRigidbody is the rigidbody component in "Player"
no we dont. we dont mind read your scripts
Should I copy the whole code or just put the file?
!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.
Alright. Is this right?
I guess, nothing here would make the camera not move, timescale =1 doesn;t do what you think it does
I know since from the tutorial I learn, timescale used for pausing the model action but thanks. I want to make it when the character opened a menu, it will also lock/stop the camera from moving just like in any JRPG, like Persona for example.
so where is the camera moved in the first place? cameras dont move on their own
Would I have to convert the quaternion values to euler in order to get my local rotation?
no, just use Quaternions and set rotation
Well... it just, something like this.
can i get some help with something please?
@queen adder Top of #854851968446365696 How to ask questions here.
sorry
awsome, so there is a script controlling the camera. Just disable whatever that is
if its only the cinemachine component doing it , then you disable that
Alright, thanks for 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.
📃 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 twice used command and dont read the bot message 😂
is alright, reading in hard xD
where is the button? i believe the two green tracks definitely not the button
btw is the button located as 0,0,0 in parent's space? it should be child of the track
I kind of tested this theory out but not in a way that you recommended, I noticed that the sprite sometimes disappears very early on, sometimes even as early as the first launch so that's not it.
Any other ideas?
It seems that I am actually able to constantly recreate it :/
I just add this force to the object at the very start:
private IEnumerator Start()
{
yield return new WaitForSeconds(2);
_rb.AddForce(Vector2.right * 100, ForceMode2D.Impulse);
}
The only other idea is to reproduce the issue and debug it.
I am able to reproduce it consistently now, how am I supposed to debug it tho?
What object?
nah man I am confused rn
Pause the game when the issue occurs and inspect the object. You want to figure out what exactly makes it invisible. Is it broken mesh? No vertices? Triangles? Maybe material going transparent? Or something with uvs?
I moved the scene camera so that the object can be seen and it's not disappearing
Maybe it's just being disabled?
moved the camera away and it's disappearing again
:(
