#💻┃code-beginner
1 messages · Page 266 of 1
its rigidbody right
Ahh okay, so slightly angled away from the ground. Check?
Yes
void Movement(){
if(currentState == movementState.Grounded && !_jump){//platform moving
if (Input.GetAxisRaw("Horizontal") == 0){
}
rb.velocityX = Input.GetAxisRaw("Horizontal") * speed;
}
That's pretty much all of the movement code at the moment
and theres a groundcheck in a seperate variable
this 3d?
2d
oh ok
Sorry, should have made that clear aha
i think there is a function for slopes
Obviously I can do Vector2.up or right for x and y, but calculating one in between?
Oh?
let me see
Alrighty
mayb this tutoiral sry i cant help much i dont rly do much 2d 😅 https://www.youtube.com/watch?v=1E8AI5UgmAw
In this tutorial I will show you how to make sure that your dynamic rigidbody driven character can handle slopes in Unity 2D.
Do you want to improve the way you write code for your games on the example of a 2d platformer? Check my video course:
https://courses.sunnyvalleystudio.com/
Is your character using kinematic rigidbody for movement? May...
no worries, will take a look
Hmm this seems like a really ehhh, hack way to do it because it switches between kinematic and dynamic haha
I think I do need to do the slope check that aeth suggested and somehow make it adjust the velocity
npnp!
I appreciate your attempt anyways
As it stands, once ive fixed this Im pretty much done with programming my character controller
then its just menus maps and fluff
im sure a lot of ppl have the same issue
Im aiming for 9 maps that if played perfectly will be completable in 5 mins each, but difficutly will make the average around 20 mins per map I think
its the type of game where if you fall, you potentially lose a lot of progress ^^
sounds like a cool game
Good for streamers and viralization ;3
yea
the gimmick is that you use a grappling hook to swing, an airdash to move in air and a hookshot to latch onto walls to combo movement
can get streamrs speedrunning
im trying to make a terrain bigger using scale tool but it isnt just working
if everything was flat, then it reuns VERY smoothly and feels good
woahhh
yea
Not quite the right place for this
this is for programming 🙂
I beleive you dontw ant to use scale for terrain as it messes up the terrain, and instead want to add more terrain segments? been awhile since i did 3d stuff
sry
ill not get a response there ever
search up on google
size options should be right onthe terrain itself
Public or Property usually
I do dislike making private properties pascal case
you cant force me visual studios
why is my particle system getting destroyed after running Erase() once?
When I run, I click, the particle effect runs, then it deletes the gameobject for some reason. I tried making it a prefab but that didn't work (I shouldn't need to..?)
Help much needed.
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.
Destroy(collider.gameObject);
That's supposed to be for the object getting erased, i don't want the effect getting erased. What's the fix?
You want to destroy the component (the particle system), but instead you're destroying the whole gameobject that contains the particle effect
or, you dont want to destroy the effect (half asleep here)
that means you need to deattach the system then if it's on the gameobject (that you want to destroy)
Guys, when I disable/enable a game object while it is playing an animation, it gets stuck on that state of the animation
This is all the relevant info
you can open the blend tree and look at it during runtime
I'm not using a blend tree
The animations seem to be playing fine, too, it's just it practically resets the default state of the revolver and rotation
usually disabling just removes update (and any rendering) from happening, but you can probably still check the duration if you want to make sure
Again, it seems to be LITERALLY changing the default transform of the revolver
probably ways about it, but a crude idea is to just stop the current animation, make sure all states are reset
How would I achieve that?
make sure all states are false (or w/e you need to have toggled to be certain that you return to idle)
Again, how would I make all the states set to false?
also you've warnings there about animation so that's probably relevant to your problem
hello, I have a cube and text like this and somehow the text never renders when I spawn in the cubeparent, anyone have any advice why?
nothing you've not done before
I've tried making it play the idle anim in the OnDisable() method. but it didn't work and gave me the "game object with animator is inactive" or something along the lines of that
A cheap fix seems to just reset the default transform of the gun ondisable, no?
This doesn't tell us much dude
ah my bad, what other info can I include?
This is code beginner, maybe some code?
Lets be a little nicer about that 😉
But yes, posting your code in a code block would be useful
this is what i got @cunning rapids @carmine turret
GameObject canvas = gameObject.transform.GetChild(1).gameObject;
canvas.SetActive(true);
GameObject canvasChild = canvas.transform.GetChild(0).gameObject;
canvasChild.SetActive(true);
_biasText = canvasChild.GetComponent<TMP_Text>();
_biasText.text = "cooltext";
I didn't mean to come off as rude or sarcastic, I was being genuine
But I apologize if I did
nah youre good
Thanks man, just give me a second
No worries, probably just how you typed it ^^
Hmmm.. screenshot the "occulsiontext" gameobject
The inspector
Also, this block of code belongs to the "cubeparent" gameobject, just in case it isn't attached there
The code looks correct at first glance, even if it looks a bit messy
yeah that's where it is yeah
I'm gonna try to serializefield the text
now I'm doing something like this with the TMP_Pro _biasText SerializedField and it still isnt working
_biasText.gameObject.SetActive(true);
_biasText.transform.parent.gameObject.SetActive(true);
_biasText.text = "cooltext";
Is the text supposed to be screen space or world space?
I'm not quite sure what that terminology means, gonna consult chatgpt and get back to you rq
I believe its world space
is the canvas set to be world space then?
where would i set that
so screen space = 2d UI
world space = 3d UI (so it gets treated like any other 3d object)
right yeah it's world space bc its above the 3d cube
how can i double-check its world space
in your canvas component
can you take a screeenshot of the inspector that you have on the "Canvas" gameobject, the parent of your text gameobject?
wait i see i found it that makes a lot of things make sense now actually let me try that
it works now! thanks so much :)
No worries! Code looked fine so I figured it must've been something in the scene setup
a couple things just clicked for me about canvases and textmeshpro bc of what you were saying here, very helpful
Whats the easiest way to calculate the position of where I want something to be, for example if I want a raycast to start infront of my players location
Like this for example
Get the current player position, get it's current orientation, calculate desired position
public float distance = 1.0f;
```example distance of the raycast
```cs
Vector2 playerPosition = transform.position;
Vector2 facingDirection = transform.right;
```Get the player position and rotation
```cs
Vector2 position = playerPosition + facingDirection * distance;
RaycastHit2D hit = Physics2D.Raycast(position, facingDirection);```Start the raycast at the new position
I'm able to incorporate the jump code into my movecment control through the Unity Input system, but I am unable to make him jump.
From this video tutorial but incorpoating it into my movement code: https://www.youtube.com/watch?v=cnSqgA4OIEk
Using the Input System to jump using the built in Character Controller.
Note that you should change the Update method to FixedUpdate in both the PlayerMovement and PlayerJump scripts for better handling of opdating the player location.
The code in question:
!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.
We need more details
In the minute mark ~4:30 in the video he adds a debug log when you press the jump key.
Does it do the same to yours?
Also, specify what you mean by "it doesn't work"
Have you tried doing some tests on why it doesn't work? if so, what were the results?
I try to have him jump w the spacebar, the character doesnt respond to the spacebar. The WASD keys work though.
Is the ground detection working?
Most jump systems have a system to check if you're grounded
I'll check on that too.
In this case (I must admit it's a bit weird), it checks the current player y velocity. If it's equal to 0, then you can jump
I prefer using raycasts but it doesn't matter
Log that part
Like the dude did in the video
I added those for sure.
An earlier friend said I should just use one characterController so I didnt add in _characterController.
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
What? What do you mean?
When I first added the jump code to my main movement code, I had both characterController and _characterController. They told me both are the same so I just added the former for streamlining purposes.
Ah alright
Should I remove the _ on the rest as well, or would it break the script entirely?
Never done that before.
In update, type cs Debug.Log(_groundedPlayer);
Returned False.
There you have it
{
isGrounded = Physics.CheckSphere(transform.TransformPoint(groundCheckOffset), groundCheckRadius, groundLayer);
}```
My Groundcheck code.
I haven't worked with CC ever before, but I feel like there are too many ground checks
Its my first time with CC. .x.
So I'm trying to see how to make it work.
Not to mention the movement code being from a different tutorial: https://www.youtube.com/watch?v=DXw9QhsjlME
Checkout the full Third Person Parkour System Course here - https://fantaco.de/unity-parkour-system
Hey everyone, in this video we'll create a Third Person Controller in Unity. We won't be using any assets to build it, we'll build it completely from scratch because it's a good way to learn the fundamentals of 3D game programming,
and it will ...
private bool isGrounded;
```Grounded bool
```cs
void Update()
{
isGrounded = Physics.CheckSphere(groundCheckTransform.position, groundCheckRadius, groundLayer);
if (isGrounded && velocity.y < 0)
{
velocity.y = -2f;
}
if (isGrounded && Input.GetKeyDown(KeyCode.Space))
{
Jump();
}
velocity.y += gravity * Time.deltaTime;
characterController.Move(velocity * Time.deltaTime);
}
```Movement logic, first line to check if you're grounded, the rest is basic CC stuff (such as gravity and input)
```cs
void Jump()
{
velocity.y = Mathf.Sqrt(jumpForce * -2f * gravity);
}```Jump method
I'd do something like this. Simple and concise
But don't take jy word completely as I've never used CC before except a few times
No worries, thanks for the help.
Hey folks, I'm having trouble with an update function on a script I attach to an object that spawns in partly-in. I have a Debug.Log at the beginning of the Update() function, and the Update() function is never called according to that even though other functions in that script work
any idea what I'm missing here?
any help is appreciated :)
_groundedPlayer = characterController.isGrounded;
//If on the ground stop vertical movement
if(_groundedPlayer) {
_playerVelocity.y = 0.0f;
}
//If Jump pressed and on ground jump the player
if(_jumpPressed && _groundedPlayer)
{
_playerVelocity.y += Mathf.Sqrt(_jumpHeight * -1.0f * _gravityValue);
_jumpPressed = false;
}
_playerVelocity.y += _gravityValue * Time.deltaTime;
characterController.Move(_playerVelocity * Time.deltaTime);
}``` Presume I don't need this one then?
- Component is disabled
- Gameobject is inactive
- Gameobject is not in the scene
- Update is misspelled
- Logs are disabled
- something else
- Component is disabled: maybe?
- Gameobject is inactive: no
- Gameobject is not in the scene: no
- Update is misspelled: no
- Logs are disabled: no
- something else: maybe?
the component works for other stuff so I would assume the component isn't disabled
well check it then
what's the difference between disabled and inactive
from my research I believe it's not disabled
Show a screenshot of the editor window with the console and the inspector visible while the game is running
I'm making a very basic VR app on Meta Quest 3 on Mac so I can't run the game through quest link
Does that mean you're not using the Unity editor?
no I'm using unity but I can't control the game with the run button
Then where does it print the logs?
Android LogCat, I'm sure it works I've been using it for hours
Think so. Comment it and check
Why is SetInt, SetBool etc of animators not available from the editor like it is in scripting?
Because they require 2 parameters and the inspector can only pass one
The editor can only pass one? Lol how did I never notice
An unfortunate restriction, thanks for the heads up : )
You can get around it by making your own function in a script and call that
how to make the animation only play when highlighted?
and how to do it reverse when not highligheted anymore
Yup, that's what I did. I just kind of like the event based approach of programming, so the use case was like this: A movable platform has two events, one for when it starts moving and one for when it stops moving. So I wanted to call the animators SetBool by just using my events ^^ Used a method instead now
Remove the ones you don't want and leave highlighted
thanks
what abt this
hi, I'm making a jump but I need to transform the directional vector of this jump from the character's local space to global space.
for instance if my character's jump is straight up (0,1,0) but my character is walking on a wall that makes the character's transform.up to be to the right I need to transform the jump vector to (1,0,0). how do I do this? I'm not very familiar with vector transformations so please dumb it down a bit xD
Isn't transform.up already in world/global space?
No that's Vector3.up
I mean, the up Vector of the transform, including the objects rotation
Hello! I've mentioned this error a few days ago and someone recommended that I look into a specific forum in hopes of resolving my problem ( I have tried ). I've looked everywhere I could possibly think of in the game files searching for the solution ( all the scripts, assets / inspector tabs ) but no luck. The problem I encounter is a *** " NullReferenceException : Object reference not set to an instance of an object " ***. I've been told that perhaps I've failed to reference an object but I cannot find my mistake. This console error occurs when I interact with an object I've set as an "Interactable item" which after interacting with should go into a inventory ( I can show the code if necessary )
I might have not expressed myself clearly, but I think that's what Alice was talking about
translating with vector.up would be the idea though in world coordinates
if you are sure it's not editor related then probably throw some script this way
True, I just had a brain fart
But If Alice wanted the global representation of the local up, then tranform.up should be used
I know for sure that in the console it does not appear as a "script error". I don't know what else it could be
Screenshot of the script or?
!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 copy - paste the code in here between the *** " ***, right?
just throw it into a paste site
Aaa ok
Now I just give you the link? ( Sorry new to this )
https://gdl.space/tinoforusa.cs ( ITEM PICKUP Script ) - The error seems to be linked to this particular script
It should or shouldn't be ?
it currently is and should not be. you cannot call a method on a null object
So I need to find my method containing the "Inventory.instance" and assign it a value?
you need to assign to the static instance field on your Inventory class
How do i spawn random animals on a Terrain?I do know how to do it on a flat land its p easy but terrain is very uneven in shape so
One second, let me find the code for the inventory.
I just want to know how to transform a vector, my jump will be controlled by wad (no s, don't wanna jump backwards) and shift to cancel out the upward part.
it's like a 3d jumpking jump.
so if I'm holding w and d the vector I need to transform is (1,1,1) normalized which I then need to change to worlds coords
this is also done using sampe, hieght?
https://gdl.space/aretuweren.cs This is a fragment of the Inventory code that contains both the static field and instance
configure your !IDE and spell your methods correctly
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
• Visual Studio (Installed via Unity Hub)
• Visual Studio (Installed manually)
• VS Code
• JetBrains Rider
• Other/None
Configure your !ide
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
Dang, too slow
On it
so does sampleheight gives us the top of the terrain at a given point?
What is this ?
it was sampleheight
I am very confused right now
there was another thing i wanted to do and i was told to do it throught sampleheight as well
Ok…and ?
and sampleheight gives us the highest point on the terrain of a given coordinate?
There is no lower or higher point at a given coord there is just a height
Oh, so basically..
(0,1,0) (up) is your jump,
by pressing W, it's then (0,1,1) (forward-up)
and when pressing W+D it's (1,1,1) (forward-right-up)
And you want to convert that Vector from local space to global space?
yes, because my player rotates a lot since I change the direction of gravity a lot, mario galaxy style walking on spheres n stuff
if it helps, this is how I transform my movement direction
Vector3 crossProd = Vector3.Cross(Physics.gravity.normalized, GetGravityDirection().normalized);
float angle = Vector3.Angle(Physics.gravity.normalized, GetGravityDirection().normalized);
Quaternion rot = Quaternion.AngleAxis(angle, crossProd);
Vector3 transMove = rot * absMove;
InputVector = transMove.normalized * magnitude;
I do not know what a cross product is though 
but it works
Just use:
transform.upin place of (0,1,0)(up)transform.forwardin place of (0,0,1)(W forward)transform.rightin place of (1,0,0)(D right)-transform.rightin place of (-1,0,0)(A left)
Add them up and normalize
Unless you're not rotating the object at all, just applying different forces / transformations
Then rotate the vectors I guess
I am rotating the object, I guess that is just the easiest way of doing it
Yup
was making it way more complicated than it had to be, typical
The best solution is the simplest solution
thanks 
Guys, my animation issue still persists, even when tweaking the OnEnable() method
Even when I MANUALLY type in the rotation through the inspector during runtime, it just reverts it back to whatever number it stopped at
Only the rotation is messed up, too
Position and scale works fine
Ok! I have setup my IDE ( succesfully I hope so )
Now what do I do? Do I just open up the code I have trouble with?
Then if you correctly specify the Awake method (including correct casing), the editor should now point out it's a Unity method if everything is correct
Okk, let me see
hi
Oh my god...
I feel so stupid right now. Apparently my dumb ass wrote "awake" instead of "Awake"
any idea why?
Heh, happends to everyone
This is why a correctly configured editor helps
Thank you for the help Fused & boxfriend & Mao ❤️
I must've been really tired when I wrote that method
any idea about it?
Yeah, I had the Unity extension in VS Code. It still didn't point out the error
I saw the spelling because I saw you writing "Awake Method" and I thought "Why do I have awake instead of Awake"
Thank you anyways 😅
VSCode is ass with C# in general and if you can use Visual Studio or are willing to pay for Jetbrains you should switch.
I'll give VS a try. Thanks for the tip
anyone?
okay I have silly question, let's imagine two coroutine and you are starting the first one in Start method. And second coroutine is connected to this first one BUT! let's imagine first coroutine is in infinite loop. Would I get crash thanks to this logic?
hi i have a problem i try to instanciate my gameObject at a distance of my mousse but when i zoom that instanciate it under the map how can i calculate the distance i have zoom or something like that
the scrolling script
float scroll = Input.GetAxis("Mouse ScrollWheel");
Vector3 pos = transform.position;
pos.y -= scroll * 1000 * scrollSpeed * Time.deltaTime;
pos.y = Mathf.Clamp(pos.y, zoom, dezoom);
transform.position = pos;
the script for instanciate my object
Vector3 mouseInScreen = Input.mousePosition;
mouseInScreen.z = 695 ;
Vector3 mouseInWorld = Camera.main.ScreenToWorldPoint(mouseInScreen);
transform.position = mouseInWorld;
if (Input.GetButtonDown("Fire1"))
{
Destroy(gameObject);
putTurret1 = true;
}
if (putTurret1 && canBePlaced)
{
Instantiate(tourelle1placable,mouseInWorld,Quaternion.identity);
}
if the map is flat you can use Plane struct and raycast at it, if its not flat, use physics Raycast
how can i use raycast for instanciate a object i never use raycast
is the map flat?
it has some collision surface right? floor?
yes
I tried creating a 3D (URP) and got this? wth is this?
use Camera.main.ScreenPointToRay(mousePos) to get the ray
use Physics.Raycast() to cast that ray into the scene
RaycastHit will contain the world point to place your object at
or use Plane, its simpler to use but it wont take into account collision meshes
ok i see i gonna try that ty guy
im not sure if this is a animation thing or code but is it possible to create a code that would throw the hammer in a parabolic trajectory? or do i need to animate it to have a trajectory?
you can use code to create an arc or meet a certain height based on the end position . . .
ohhh thanks cause im trying to make a replica of the mario enemy wherein it throws hammers in a parabola XD
hey guys. can smb help me out? i have this piece of code:
public class PlayerInteract : MonoBehaviour
{
// Start is called before the first frame update
void Start(){
}
// Update is called once per frame
void Update()
{
float interactRange = 2f;
Collider[] colliderArray = Physics.OverlapSphere(transform.position, interactRange);
if (Input.GetKeyDown(KeyCode.E))
{
List<GameObject> gameObjects = new List<GameObject>();
foreach (Collider collider in colliderArray)
{
var npc = collider.GetComponent<NPCInteractable>();
if (npc!=null)
{
float distance = Vector3.Distance(npc.transform.position, transform.position);
Debug.Log("NPC position: " + npc.transform.position);
Debug.Log("player position: " + transform.position);
if (distance > interactRange)
{
npc.EndConversation();
}
else
{
npc.Interact();
}
}
}
}
}
}
and when i press E, i get 4 NPC instances logged. How can it happen? Can smb help me out? Thx
that's definitely feasible . . .
could someone come to #🏃┃animation and help me
This is a coding channel, and not an animation channel. There is a reason channels are divided in categories so please stick to it.
Does an enumator coroutine have to be called in an update function?
You could, but that's not the point
A coroutine has to be called once with StartCoroutine()
Log the GameObject name for the NPC to see which objects they are . . .
It's just that this only seems to change the alpha of the image when I first click, and doesn't do the smooth change that I'd like
private void Start()
{
playerControls = new PlayerControls();
playerControls.BasicMovement.Aim.started += SwitchToAimCam;
playerControls.BasicMovement.Aim.canceled += SwitchToBodyCam;
playerControls.Enable();
}
private void SwitchToBodyCam(InputAction.CallbackContext obj)
{
mainCamera.SetActive(true);
aimCamera.SetActive(false);
currentReticleFade = 0f;
StartCoroutine(FadeCrosshairOut());
}
private void SwitchToAimCam(InputAction.CallbackContext obj)
{
mainCamera.SetActive(false);
aimCamera.SetActive(true);
/* Fade time to control duration of fade
*/
currentReticleFade = 0f;
StartCoroutine(FadeCrosshairIn());
}
private IEnumerator FadeCrosshairIn()
{
if (currentReticleFade <= reticleFadeTime)
{
currentReticleFade += Time.deltaTime;
reticleAlpha = currentReticleFade / reticleFadeTime;
Color newColor = new Color(aimReticle.color.r, aimReticle.color.g, aimReticle.color.b, reticleAlpha);
aimReticle.color = newColor;
yield return null;
}
}
private IEnumerator FadeCrosshairOut()
{
if (currentReticleFade <= reticleFadeTime)
{
currentReticleFade += Time.deltaTime;
reticleAlpha = 1 - (currentReticleFade / reticleFadeTime);
Color newColor = new Color(aimReticle.color.r, aimReticle.color.g, aimReticle.color.b, reticleAlpha);
aimReticle.color = newColor;
yield return null;
}
}
i never asked the question here i got no response and this is 1 of the most active channel so i just said someone to see that
That does not make this any better. Use channels for what they are meant for and don't crosspost for help
i have only one npc Girl1NPC, so its only this object
What part is expected to change the alpha?
The section down here Color newColor = new Color(aimReticle.color.r, aimReticle.color.g, aimReticle.color.b, reticleAlpha); aimReticle.color = newColor;
It does correctly change the image, but it's just on or off, with no smooth transition
Your Coroutines all have a single yield return null; in an if-statement. This means the method starts, checks the if-statement, changes the alpha, waits 1 frame, and then ends
Perhaps you want this if-statement to be a while loop?
Right now yield return null; does nothing but wait a frame and then nothing at all
Was a bit confused by what that return actually does, I was under the impression that would start the routine again
So my guess is you need to change the if-statement to a while loop
guess I was wrong
No, a yield statement defined the delay basically
This doesn't run until the alpha is 0 or 1. You need a while loop with a condition to check until it's complete . . .
Unity will wait this period before resuming the method
Does it have multiple colliders?
Ah, so it doesn't start it again, just continues it
You still need to define the flow of resetting yourself
let's see if this works
Your code only logs the npc position and the player position but there is a log for the npc name that appears. Is that in a different script?
ay! It works!
Alrighty then, that makes sense. Can use that in other places now then
thanks for the help
So if yield return acts as a delay, can I use that to control how many seconds elapses between each run of the routine?
See Coroutine time delay
Okay nevermind, looks like it barely explains the different yield statements. There are a lot of different yield instructions you cna use, like waiting for seconds, until the end of a frame, but also with predicates to wait until something becomes true
oops. my bad. yes there is:
public class NPCInteractable : MonoBehaviour
{
[SerializeField] private NPCConversation npcConversation;
public void Interact()
{
Debug.Log(this.gameObject.name);
ConversationManager.Instance.StartConversation(npcConversation);
}
public void EndConversation()
{
ConversationManager.Instance.EndConversation();
}
}
ok sry
I wanted to find the no. of rabbits in the world through this line.I saw it in some learn.unity tutorial and remember it was written somethign like this but cant remember How."RabbitSpawner" is the name of the script
Use plural FindObjectsOfType rather than the singular variant
that line of code makes no sense
the .length is not supposed to be there but idk wht was
Why would it make no sense? That line is perfectly valid apart from the fact a Find type method is used
You just used the singular variant rather than the plural
oh it was jsut Length and not length
even so. it a singular find so how can it have a length of anything other than 0 or 1
thx it worked too now lemme just see if its working the intended way
The question was why it was not possible to count the number of spawners, which is because they used the wrong method
Not why Length can't be used for a single result
indeed
how do i do so that only a specific numberof rabbits spawn like a 100 and once 100 rabbit spawns through instantiate it stops spawning until 1 dies
Have a general manager keep track of what spawner is allowed to spawn a rabbit and have it keep count of the total spawned
then use if statement to stop spawning if it reaches 100?
For example
If you want to keep a shared context between multiple spawners you would at least need a general manager that can keep track of this.
i think i understand
Then either have it spawn the actual rabbits on defined spots rather than having individual spawners, or have the spawners communicate with the manager by having a singleton pattern in some way.
I'd pick the former
here is an example
IEnumerator Spawn()
{
while (loop) {
yield return new WaitUntil(() => Count < maxEnemies);
yield return new WaitForSeconds(Random.Range(3, 10));
float angle = Random.Range(0f, 359.99f);
point.x = Mathf.Cos(angle) * (radius+15f);
point.z = Mathf.Sin(angle) * (radius+15f);
GameObject go = Instantiate(prefab, point, Quaternion.identity);
Count++;
enemies.Add(go);
}
}
Count is decremented when an enemy dies
thx lemme try
Is it possible with a Collider2d, to have it detect collisions between like the ground, but not collide with the player, but still send triggers/collision when the play and it "collides", without them actually colliding and not being able to move into each other
Just going over in my head how i'd implement a damage system. Is there much of a difference between having a health component that controls the current health value, which the player class can then reference, to having an interface with methods to adjust player and enemy health in their respective scripts?
bruh my jump function suddenly stopped working
Theres no problem then why is the character not jumping upon pressing Jump
Is OnEnable called when the parent is enabled after having been disabled?
i did find the problem when i touch the ground instead of making the bool Isgrounded true it makes it false.
does the object have multiple colliders? change colliderArray from a local variable to a public field, then you can see from the inspector if they are from the same GameObject . . .
That's why I'm asking
Hello guys. I got a question regarding weapon switching. I have a script that switches weapons for me when I press the alpha 1 and 2 keys (etc.). I made sure that when the weapon is disabled, it resets the animation controller and disables the "isReloading" state of the scriptable game object it is referencing. However, while the "stop reloading" aspect works fine, the animation still gets stuck in that weird state in the reload animation. it seems to be LITERALLY changing the default transform of the revolver
This function is called when the object becomes enabled and active.
Technically it was never disabled, only its parent was
But then again it is now
then i would place a log inside of OnEnable for the child GameObject. when the parent is enabled—after being disabled—check if the log appears. then you know if OnEnable will be called . . .
Gentlemen. I need help. I've been working on this for quite a while. The only solution I came up with is a cheap fix to disable all weapon switching while you reload
Funnily enough, it seems like I'm facing a quite similar issue
could someone help
The Isgrounded bool telling us if we are on the ground or not disables when we are actually on ground but it shouldnt be this way .I dont understand why is this or how to fixc ir
Log ground check
That's usually the most common cause
log?
Debug.Log();
oh
this
it takes a min to load the game
Dude
Here
Not a string, debug the boolean GroundCheck
i did that
If it returns False, you have your answer
My guy. Your boolean for ground check is called "isGrounded"
oh wait
There you have it
Your code doesn't allow you to jump if it's false
Show me the scene
one sec
Specifically, the position of your "Ground Check" game object
It should be slightly below or at the player's feet
those arrow is the groundcheck
yea
"isGrounded" acts like your feet
i wrote it bruh
Alright, what is your ground layer supposed to be?
Is it the second picture?
This your ground check? Is it attached to the player game object? Is the floor the correct ground layer?
the groundcheck is the arrow in 2nd picture
yea
Show me the inspector for the movement code
Make sure your terrain has the correct layer for "Ground"
dint apply ground layer to it :/
or whatever you called it idk
thats ground
There you go
i need to focus more. i didnt apply the layer when i made the new terrain
I know, you need to be "grounded" to jump
Happens to the best of us
yep its working
finnaly spent the whole day on just the animal spawner and this jump
will setup the spawner tomorrow
thx
Wrong Layer is a very easy mistake to make
Yo fen
Your thing with my weapon problem worked yesterday
Thanks
Using Scriptable Objects helped
Hi, yesterday I got recommended to switch to Unity Event system for making my multiple triggers work. I've set it up and I'm getting notifications when touching each of them, but my problem wasn't that, more of how to know which one was touched.
https://paste.mod.gg/biegbuvflnfu/3
Sounds like you need to be able to pass an argument.
did you figure it out?
I can pass an argument, but I'm trying to avoid using the name of the trigger object as a way of identifying. So what else could be passed to identify?
You could use more scriptable objects here, I suppose
What do these triggers represent?
Are they mostly going to be "right" and "wrong" triggers?
Colored it to make it easier to see, but the idea is for me to know which trigger the player touched out of these
Depending on the map wrong and right would be depending, so don't worry about that.
When you say scriptable objects, could you elaborate
I'm still quite new to Unity
My first thought was to just have the trigger manager pass itself, and to then reference the trigger managers from the script that's deciding what happens
you linked the code for one in your original post...?
https://paste.mod.gg/biegbuvflnfu/0
A tool for sharing your source code with the world!
But it looks like you're trying to explicitly avoid direct references here
since you're running everything through this GameEvent system
Yes but I mean in how to use them :)
I have to wonder if you actually need any of this
Anyway you should make these things pass themselves in as a parameter to this event
Aren't you already using it?
You called these "Unity Events", but these are not unity events
Yeah I tried that before, but I wasn't sure how I'd compare it to check which one was being fired off
UnityEvent is used for things like the "on click" events on a button
Yes, but how to use them in the sense of knowing which trigger.
[SerializeField] TriggerManager wrongTrigger;
[SerializeField] TriggerManager rightTrigger;
void Awake() {
wrongTrigger.RegisterListener(BadThingHappens);
rightTrigger.RegisterListener(GoodThingHappens);
}
in this case, you just register different listeners for different triggers
(this code does not match your current code -- you're directly registering with a TriggerManager)
Thew code you have here is good for making very decoupled game logic
like "do something any time an entity's health reaches 0"
Yes thank you it appears it is being called
But this is not appropriate for setting up very specific one-off interactions.
Well it's not a one off thing
I wouldn't create a global event bus to handle a button that opens a door
The button will only ever do one very specific thing: open a door
The button should just directly reference the door and tell it to open
It's a core mechanic like the health example
(or the door should directly subscribe to the button)
Have you seen the game "Exit 8", I'm making a small project to learn game development a bit, and trying to make a copy of that
are you creating something like Antichamber's infinite hallways?
Not sure what that is
It's a game based heavily around impossible geometry
which it accomplishes through a mixture of teleporting the player and Weird Shaders
Most simple way to describe what I'm doing is:
Playroom you look if there is a diferrence or not compared to the first room you spawned in. If there isn't, you walk forward, if there is, you walk backwards.
Between each level there is an area for a sign to show which level you're on.
If you were right about differences (or none) it goes up, if you were wrong, it goes down.
And I thought about player teleporting, but in the long term I believed that spawning and despawning would be easier.
Okay, so all of these events are going to be either "success" or "failure"
in that case, just pass a bool
which will mean either:
- right or wrong
- change or no change
I have 2 type of maps
the latter may be easier to deal with, since you won't have to tell the trigger managers about the correct answer
The normal map has the "correct trigger" in front, reverse is opposite ofc
they'll just indicate which answer you chose
A scriptable object just holds data that different scripts can reference
And interact with
You can make one by creating a ScriptableObject script instead of MonoBehaviour
So I have 2 triggers for that on each, and then a 3rd that I would be at the "start" of the current level to handle despawning of previous map and changing the level sign area behind to the correct one.
As I showed before
You've already probably used lots of MonoBehaviour-derived classes. These are a kind of component (which is, itself, a kind of unity object). Components can be attached to game objects.
A ScriptableObject is another kind of unity object. It's not a component, so it can't be attached to a game object. Instead, you can store scriptable objects as assets -- much like a prefab, a texture, a material, etc.
hey guys, don't know where to ask about IDE/code editor problems with unity, so sorry if this an off-topic
I'm trying to move from Visual Studio 2022 to VS Code, but after proper setup by guide with packages, settings, extensions, etc. - VS Code is not compiling on save until I alt+tabbed back to unity, but intellisence, code completion, etc. is working fine still
am I doing something wrong? asset refresh in settings is checked both in Unity and VS Code, but it's not triggering at all
I found extension for VS Code that forces refresh, but I hope I messed up something during setup and just haven't done something, because Unity extension supposed to do that by itself
since a ScriptableObject is a unity object, you can serialize references to them in the inspector
Right, ok, I wasn't sure about the terminology
I'm usually trying to prevent Unity from auto-refreshing :p
There shouldn't be any distinction between VS and VSCode here.
Unity is just looking for file changes.
In the script "mapspawning" I already have a temp bool for that purpose
I'm just very lazy to alt+tab after I'm done editing code or adding a new file, that's a problem
But even if I pass a bool, how am I supposed to know if I should set it to true or not?
I still don't know which trigger is actually being touched?!
there are only two choices, yes?
"change" or "no change"
Yes. So for example how do I pass a bool with the true value to represent "changed"?
All I know now is that a trigger is being touched
How do I know if it's the "CorrectTrigger" or "WrongTrigger" that the player is touching
You're going to need to modify GameEvent
it currently can't receive any arguments
Raise needs to take a bool parameter
Yeah done that
also, I see you have UnityEvent in GameEventListener after all
so switch that from UnityEvent to UnityEvent<bool>
(i'd missed the other files)
er, actually, you'll need to do this:
[System.Serializable]
public class LevelChoiceEvent : UnityEvent<bool> { }
then
public LevelChoiceEvent Response;
Unity can't serialize fields with generic types in them (except for a few things, like lists)
public UnityEvent<bool> Response; wouldn't serialize
so you wouldn't be able to see Response in the inspector
You can declare that class wherever you want. I guess I'd put it in the same file as GameEventListener.
If I'm using UnityEvent<bool>, what would I use for the invoke method as an arguement?
OnEventRaised will need to take a bool
since OnEventRaised now needs a bool, Raise will also need a bool parameter
Yeah, but what do I put in raise when I call it
and since Raise now needs a bool parameter, TriggerManager needs to pass it one in its OnTriggerEnter method
TriggerManager will need to store a bool field that indicates if it's the "Change" or "No Change" trigger
and that's where the chain ends!
I still need to give Invoke() something
Since we're now using UnityEvent<bool>
indeed -- you'll pass it the bool parameter that OnEventRaised receives
Ah, right
so:
- TriggerManager has a bool field that it passes to GameEvent.Raise
- GameEvent.Raise passes that parameter to GameEventListener.OnEventRaised
- GameEventListener.OnEventRaised passes that parameter to LevelChoiceEvent.Invoke
and thewn LevelChoiceEvent.Invoke winds up running all of its listeners, passing them that bool parameter
Yeah, that all works nice and dandy
I'm still unsure how we can decide if the bool should be true or not depending on which trigger is touched
TriggerManager needs a bool field.
If you know which one is which, just set it up in the inspector
check the box for the "Changed" trigger
That bool will not be "right" or "wrong"
I mean, it can be, if you pre-author each level and know the answer already
I have that.
I was imagining something where you randomly generate a "changed" or "not changed" level
and then you just wait to see which trigger the player chooses
and, in response, you decide they were right or wrong
This way, you don't have to mess with the triggers for every single level
Their meaning is constant: "Change" or "No Change"
Keep the game logic out of the triggers.
I'm gonna be completely honest and idk if I'm just extremely slow or something. But I still don't see how this setup allows for me to know which trigger is touched. You say "set it up in the inspector" but from the picture here, how would I do that?
There are only two triggers, correct?
"Change" and "No Change"
Well 3, but yeah mainly 2. Don't worry about the last one.
If there are more than two options, you need to handle that.
There are only correct or wrong
Last one is just for spawning things, I'll figure that out.
Okay, so the third kind of trigger is completely unrelated to these two
The "Change" and "No Change" triggers.
Yes
Rename that field to "Changed". It will be true for the "Change" trigger and false for the "No Change" trigger
When you touch one of the two triggers, the bool will be passed to GameEvent, which goes to GameEventListener, which invokes all of its listeners.
Suppose I subscribed this method to my GameEventListener.
public void ChoiceMade(bool changed) {
if (changed == correctAnswer) {
Win();
} else {
Lose();
}
}
if correctAnswer is false and changed is true, that means:
- The level had no change
- The player touched the "Changed" trigger
So, you lose
Yes, but the bool value is never changed?
When is the value of Change set to false or true on each corresponding trigger?
because you checked the box on the "Changed" trigger...
[SerializeField] bool changed;
void OnTriggerEnter(Collider other) {
onTriggerTouched.Raise(changed);
}
Why is the Wheels Collider so far down
Right, ok so that's what you meant by the inspector.
Ok, yeah perfect. I'm really still new to Unity and only know slight few things. Thanks for the help 👍 😁
private void Moving()
{
Vector3 dest = _grid.GetPositionCell(_index_grid);
if (Vector3.Distance(dest, transform.position) > 0.1f)
{
Vector3 lerp = Vector3.Lerp(dest, transform.position, _speed_move);
_rb.MovePosition(lerp);
}
else
{
_rb.MovePosition(dest);
_is_moving = false;
}
}
Does this method needs to be run in update to work properly?
I mean... when I run it just as method from non-update... it only gets that RB around 30% of the distance...
So I guess the answer is it has to be run in update or ienumerator
MovePosition should only be in FixedUpdate
not Update
also that's definitely an improper usage of Lerp
okay... I got this code from a guide so yeah... I believe you that it's improper use
Read this on how to lerp correctly
surely the guide told you were to put it 🤔
I think I will simply get rid of lerp since I don't plan using it anyways and I plan to use MoveTowards + Animate the character running
so this part is irrelevant, altho for self-education I willread the docs
what about MoveTowards? also needs Fixed Update or update?
if there is physics involved and you are moving it use FixedUpdate
MoveTowards is just a math function. It should be used as needed where needed
MovePosition is actually a thing that moves the Rigidbody and its effect gets queued up to happen in the physics update, that's why it needs to go in FixedUpdate.
These "rules of thumb" are actually all just stand-ins for actually understanding how these functions and methods work and applying your knowledge to get the effect you want.
In reality there are no rules, but these things like "only use MovePosition in FixedUpdate" are designed to keep things working properly without thinking too hard.
Use the proper channel for your question #🔎┃find-a-channel
@sour yew This is a coding channel, which is for coding questions. Not for materials.
sorry. m ybad. ill delete my msg
sorry, is there some pre-defined method to turn the gameObject towards the target it's moving to?
or it's actually there by default?
Transform.LookAt?
for a Rigidbody though you'd probably want to use MoveRotation or set the RB's rotation with Quaternion.LookRotation
nah, I switched from RB to transform.position. My rb has different purpose
those two may not be in sync
if you're doing physics it's usually best to deal with the Rigidbody
private IEnumerator MoveThePlayer(Vector3 dest)
{
dest = dest + new Vector3(0, 0.5f, 0);
if (is_moving)
{
yield break;
}
is_moving = true;
while (MoveToPosition(dest))
{
yield return null;
}
PlayerState = PlayerStates.IDLE;
is_moving = false;
}
private bool MoveToPosition(Vector3 target)
{
return target != (transform.position = Vector3.MoveTowards(transform.position, target, animSpeed * Time.deltaTime));
}
done it like this
nah, that RB is just needed to trigger some "events", nothing more
thank you
its better if ya use rb, even if u arent working with physics rn, its for if later ya need
Hey I'm using mouse deltas to control the rotation of my camera, but you can visibly see the ticks between the angles when you move the mouse slowly. I tried slerping but it doesn't keep up with the natural movement of the mouse, and when you move quickly the rotation tends to bounce back
how would I smooth out the rotation for slower turning?
the game I am working with does and will need literally 0 physics.
Not 0... physics, but... I mean I am not going to use physics at all
it's turn based game without any physics. I won't be needing to jump or something. And I will definitely get away with MoveTowards and so on.
https://gdl.space/akafomegub.cs
here's what i'm working with
attempt one bounces in the other direction at high speed, attempt 2 just doesn't work
ur first attempt looks the closest
just needs a slerp
and i know u said u tried it.. but it was most likely implemented incorrectly
yeah i just don't know the variable to slerp over
yeah so i slerp the current rotation to the new one, but I don't know what to put for the float to smooth it out but not cause bugs
since ur rotating it in update u'd probably want to use some modifier multiplied with time.deltaTIme;
and then adjust that modifier in the inspector until it rotates like u want
yeah, delta time felt nice at slow speeds, but at higher speeds it bounces. so I need my modifier to increase at larger mouse speeds
so I tried multiplying by the magnitude of mouse delta
but that didn't work
because mouse delta's in pixels
so then I divide mouse delta by the magnitude of the width and height of the screen
and my camera doesn't rotate
void Update()
{
// Calculate the target rotation based on mouse input
float targetYRot = yRot - mouse.delta.y.ReadValue() * Time.fixedDeltaTime * panSpeed;
float targetXRot = xRot + mouse.delta.x.ReadValue() * Time.fixedDeltaTime * panSpeed;
targetYRot = Mathf.Clamp(targetYRot, yMin, yMax);
// Smoothly interpolate the rotation using Quaternion.Slerp
Quaternion currentRotation = transform.rotation;
Quaternion targetRotation = Quaternion.Euler(targetYRot, targetXRot, 0);
float slerpSpeed = 0.1f; // Adjust this value for the desired rotation speed
transform.rotation = Quaternion.Slerp(currentRotation, targetRotation, slerpSpeed);
// Update strafe and accel variables
strafe = Input.GetAxis("Horizontal");
accel = Input.GetAxis("Vertical");
}```
it'd look similar to this, where ur building ur rotations before hand.. and then slerping
for slerpspeed I don't want to limit the speed of rotation. I want it to line up tith the normal rotation, the slerping is just to smooth out the sudden ticks at lower speed. that's what I'm not sure about
but I should work on comments and organising anyways
not sure i understand.. ur normal rotation (w/o smoothing) is just gonna be what it is.. its smoothing that prevents the jerky and snappiness
w/o it.. it would still be jerky.. u would need smoothing but very little of it
this is the new input system? i always had issues w/ mouse delta's
yeah, i'm using the slerp function to prevent the jerky rotation
yes it's the new input system
theres tutorials i found not too long ago that showd ways to use mouse delta w/ different settings in the input system that kinda helped w/o doing any smoothing in code.
let me see if i can't find one of em for reference
the actual problem/fix starts @ 1:00
Thank you all for the help, got it done, so far movement and so on works like intended
Hm. I think the issue might not be the input system but rate just the update rate or the precision. my setting was already on dynamic.
oh, well they probably started using that as the default setting since ive used it
yeah, probably
the stutter isn't it not receiving or overcompensating for a movement, but it's like a 10fps rotation as opposed to sixty or smth
I poll for my player input the old system so i have no examples i can look at of my own to help out w/ ur setup
well I guess i'll live for now, it's a mild QoP issue
i simply use a basic slerp for rotation
and i multiply my inputs by a sensitivity modifier (for the speed)
ya, you wont forget about it but it is important still..
player movement / feel is 1 of the more important things
Hi I have a question, if two gameobjects collide and i want them to be a trigger and not to actually collide, is it fine to have a rigidbody and a collider with no trigger on one gameobject and just a collider with on the other gameobject with the trigger on? sorry if i explained it bad im new to unity
yes
but another route (if u dont want any interaction to happen) and u just want it to pass thru.. u can set Include / Exclude option in the inspector to ignore each other..
I think my issue her is that if I move my mouse at a moderate speed, it covers more than 180 degree rotation, so the slerp bounces back to chase the shortest path to the new rotation
then transform.position will do the work, keep it up
or can set up layers and use the layer matrix in the physics settings of the project settings to have two layers ignore each other
thats a good observation
could very well be whats happening
so how do i maintain a "path" to slerp through?
and thats what will happen.. if 1 direction is closer to the other.. its gonna take the shortest path
would I need to set up an enum to track the iterations of rotation and ensure each rotation is met?
simple fix would be to clamp ur mouse delta... so it only lets u rotate in certain increments
thats overcomplicating it i think
// Smooth mouse input
Vector2 mouseDelta = new Vector2(mouse.delta.x.ReadValue(), mouse.delta.y.ReadValue());
smoothedDelta = Vector2.Lerp(smoothedDelta, mouseDelta, smoothingFactor);```
could also smooth ur delta before u use it
oh wow
just brainstorming for ya
let me see how that works ill be a sec
to me i work in iterations / trial and error.. when people post issues with movement code its always a challenge to know what will work and whats best..
b/c w/o the context and the lead - up to what u have.. its harder to troubleshoot little issues
I want it to display "hit" to the console when they collide but right now they just go through each other
isKinematic rigidbodies dont respect collisions
it'll have to be a regular rb to trigger isTrigger colliders
you are awesome
amazing
perfecto
void Update()
{
yRot -= mouse.delta.y.ReadValue() * Time.fixedDeltaTime * panSpeed;
xRot += mouse.delta.x.ReadValue() * Time.fixedDeltaTime * panSpeed;
deltaRot = new Vector2(xRot, yRot);
slerpRot = Vector2.Lerp(slerpRot, deltaRot, Time.deltaTime);
yRot = Mathf.Clamp(yRot, yMin, yMax);
strafe = Input.GetAxis("Horizontal");
accel = Input.GetAxis("Vertical");
transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.Euler(0, slerpRot.x, 0) * Quaternion.Euler(slerpRot.y, 0, 0), smoothSpeed);
}
```
it's perfect
messy but perfect
👍 glad it works
Time.fixedDeltaTime needs to be removed
it's kind of less wrong than just Time.deltaTime, since at least it's a constant
yea ur delta is gonna be frame-independent anyway
it's doing nothing except dividing panSpeed by 50
mouse input is a distance
but yeah
it is not a rate of change
just a simple constant should be enuff
People usually use Time.deltaTime by mistake there
which winds up giving you very weird mouse input
the longer the frame, the larger deltaTime is -- and the more the mouse has moved in that frame
so as your game gets slower, your mouse gets more sensitive
is there any way to make it work without disabling kinematics?
soo i edited unity's URP template to make this readme.. it works and all but I get this error when opening the project
AmbiguousMatchException: Ambiguous match found.
System.RuntimeType.GetMethodImplCommon (System.String name, System.Int32 genericParameterCount, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConv, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) (at <eef08f56e2e042f1b3027eca477293d9>:0)
System.RuntimeType.GetMethodImpl (System.String name, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, System.Reflection.CallingConventions callConv, System.Type[] types, System.Reflection.ParameterModifier[] modifiers) (at <eef08f56e2e042f1b3027eca477293d9>:0)
System.Type.GetMethod (System.String name, System.Reflection.BindingFlags bindingAttr) (at <eef08f56e2e042f1b3027eca477293d9>:0)
ReadmeEditor.LoadLayout () (at Assets/Spawn_Readme/Scripts/Editor/ReadmeEditor.cs:73)
ReadmeEditor.SelectReadmeAutomatically () (at Assets/Spawn_Readme/Scripts/Editor/ReadmeEditor.cs:63)
UnityEditor.EditorApplication.Internal_CallDelayFunctions () (at <bf6080dbf0564cf1b405dfd6e0dac725>:0)
static void SelectReadmeAutomatically()
{
if (!SessionState.GetBool(s_ShowedReadmeSessionStateName, false))
{
var readme = SelectReadme();
SessionState.SetBool(s_ShowedReadmeSessionStateName, true);
if (readme && !readme.loadedLayout)
{
LoadLayout();
readme.loadedLayout = true;
}
}
}
static void LoadLayout()
{
var assembly = typeof(EditorApplication).Assembly;
var windowLayoutType = assembly.GetType("UnityEditor.WindowLayout", true);
var method = windowLayoutType.GetMethod("LoadWindowLayout", BindingFlags.Public | BindingFlags.Static);
method.Invoke(null, new object[] { Path.Combine(Application.dataPath, "SpawnReadme/Layout.wlt"), false }); // the error is here..
}```
it worked before I changed the name / directory
but all i have done is renamed the folder from TutorialInfo to Spawn_Readme
and changed the matching strings in the Readme.cs script
SpawnReadme not Spawn_Readme
ohhh! really?
changing strings shouldn't be causing an error when trying to resolve the method group, though...
method.Invoke(null, new object[] { Path.Combine(Application.dataPath, "SpawnReadme/Layout.wlt"), false });
yea, ive had this issue before and i couldnt figure it out
so i gave up on it until now
let me try w/o the underscore
if i mark the readme.asset as isLoaded = true it doesn't error.. but that was just bypassing it lol
not that i know of
oh I see path string in the code is different from the folder name
I don't see any method that matches what you're doing, though -- there are only two methods named LoadWindowLayout and neither takes one string and one bool argument
yep
dynamic rigidbodies. are kinda the important part to detect collisions
yeah theres an underscore in the folder name but not in the code
Did the code work before you renamed things?
ya, it still shows the readme if i select it.. but it doesn't load up on first start
like unity's did.. but yea i didnt catch that typo
i got it right up here 😄
thanks for the eyeballs man
do i need to learn how to save the grid and load it or do i just need to make a scene asset for each level
https://www.spawncampgames.com/paste/?serve=code_52 full version of the Editor script if anyone interested
one of the most difficult tasks to master in software development is to see what is actually there rather than what should be there
pre-me-fukin it up 😄
i looked at it 4 or 5 times before posting it 🤦♂️
rofl
neeed direction
i copied the setup after i modified it and pasted it into other projects w/ their meta files..
question being.. the instanceID isn't a problem b/c of the meta files being transfered along side it?
it worked fine after recompiling.. so i guessing its a non-issue
I reproduced this by messing up the file path. That's very weird.
mmhmm its not hard to do 😄
i was worried about that layout.wlt file..
b/c i have no idea how those work
but seems u keep the directory intact its pretty easy to copy over/ move to other projects locations
oh, actually..
no, it's not just when the path is messed up
The code just doesn't work at all.
Hello guys, I found this extremely satisfying and relatively simple recoil system on youtube, however, with its implementation I was wondering how would you set different recoil values for different weaponss, if they all follow the values of a single parented object?
Newest video! (The Craziest Dev Challenge I've Ever Done) - https://www.youtube.com/watch?v=x7js1DhgEi8&ab_channel=Gilbert
Welcome to my first tutorial for Unity!
In this tutorial I show you how to use recoil to make your guns a lot more punchy! Unfortunately this tutorial doesn't show you how to animate your weapons for the full recoil effect....
it works on first load
can't say after that tho..
Does it actually run, though?
well something has to make it focused to the readme when the project opens
That's not what the method does
The method loads a layout
There's a separate method to select the readme asset
ohhh ya, i cant say if that parts working or not..
my layout always looks like my last version i used
but it does set the bool to true
lol..
you'd modify that value of hte parent object.. / per weapon
yep, bingo
or extract it and put it on the weapon.. and have it read the value from there instead
cracked open the template
loadedLayout: 1
loadedLayout is set to true in the template and the code never runs
Soooo... basic script comms?
mmhmm
I'm guessing that Unity removed the matching LoadWindowLayout method and replaced it with a TryLoadWindowLayout
But since they were using reflection to access the internal methods, this refactoring wasn't noticed
ahh, i think imma just remove that part.. i dont need it to force a layout.. it was meant to show dependencies.. so if u click the readme asset..
and they just wound up giving up on loading a layout entirely
the readme will still be drawn in the inspector..
yeah, there's no point in trying to load a custom layout anyway
the entire thing should just be removed
nice.. thanks for looking mate 🙂
if (readme && !readme.loadedLayout)
{
//LoadLayout();
readme.loadedLayout = true;
}``` fixed lol
now i can remove the reflection stuff
Hello, I'm currently on a school project. In this school project I have a Cylinder Gameobject ("electrode") and another Cylinder GameObject ("electrode holder"). "electrode holder" is a parent from "electrode". "electrode" 's scale following the Y-Axis is being modified. I want to be sure the "electrode" 's face facing "electrode holder" stays at the same position. How can I do ?
Thanks
how does scaling it change the rotation?
either way.. if ur modifying the transform of a child object. best to make sure that the parent is scaled to 1:1:1
Electrode_Holder and Electrode are both 1:1:1 across the board..
i scale the _Graphics obj's instead..
then u can do all ur other stuff (movement/rotations/etc) to the Root obj's
and since they're 1:1:1 they should be fine
scale the graphics (rotate the parent) -> this will keep dimensions and stuff the same
if u scale the graphics and (rotate the child) -> this will break ur scales and cause weird stuff
I'll try on my side (my electrode holder is not 1:1:1).
In case I need to use colliders, on what Object do I apply it ? The project is to simulate some electrode soldering (so the electrode is consumed when in contact with the table)
@rocky canyon Yo so like, how do I change the values of the recoil script through the revolver script:
.
Im a bit confused about coordinates, if I move an object from one end of my terrain to another supposed on the same axis I get: FROM: World space: Vector3(-8852.64, 76.46, -1066.66) 884.997,-6.044,3 (local space)
to: World space: Vector3(-8852.64, 99.11, 0.04) -181.701,16.606,3 (local space). World space is obtained from using the .transform property. I dont understand why I didnt move it on the Z axis in the local space ? the object has a rotation of 0,90,0
is the code showing world coords not correct ?
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/member-access-operators
the local space was obtained from the transform x,y,z in the inspector while the object is a child of the terrain gameobject
are the axis inverted in world space or something ?!
If the Z axis didn't change in local space, it's because this object never changed Z distance to its parent's origin
cuz it seems my translation along the X axis in local space was done on the Z axis in world space...
you have ommited the most important information. How are you moving the object?
Entirely possible. If the object is rotated, the local X axis absolutely could be the world Z axis
by dragging the blue gizmo in the scene
ie:
which arrow, and is your gizmo set to world or local
so you are using the object forward
and I adjusted height with the green arrow
huh no idea how to know if it is local or world. I guess that would be somewhere in unity learning
It's the box on the top of scene view window
So, was this gizmo in local or global?
so local
Okay, so, if the gizmo's in local space, dragging the green arrow would change the local Y axis
There is no way to know how this might affect the global position on any particular axis
I should set the gizmo to work in world space then ?
I don't know what you're trying to do, so I don't know what you "should" be doing
Yup that does it, immediately worked
The more I code my game, the more it starts looking like just a bunch of spaghetti code
Anyways, thanks @polar acorn
well Ill try to put into words what Im doing cuz I have no idea myself and come back
it depends.. if a script is interacting with the colliders it needs to be on the same object..
if ur using colliders for a rigidbody then all child colliders get combined into a composite type collider (so as long as the rigidbody is on the parent)
the removed comment, i think it was b/c you hadn't declared a variable named hit
in the doc's for raycast u can see here they delcare a RaycastHit called hit.. and then the function uses that variable
thats part of it.. when first learning ur just learning new things... as u get better and ur project grows thats when u realize all the optimization stuff and the more complex stuff for structuring code.. that u flew past during learning was more important than expected..
so u go back learn about it more. and start refactoring ur code.. *this time using more coding practices that allow for optimization/ expandability
Can anyone help me with making a world in vrchat im a 3D designer not a coding exspert so wjag should i lear what code (U# ,udon ,)
!vrchat
Join the growing VRChat community as you explore, play, and create the future of social VR! https://discord.com/invite/vrchat
Yes im in that but what code shoild i
Use
what do you mean what code?
Ask them
ask the community which knows about this specific plugin workflow..
U# and Udon are not Unity concepts. They are VRChat constructions. You're not really going to find people here who know what that means
The VRChat discord is the place to ask this
My camera isnt attached to my cameraholder for some reason, my cameraposition (first pic) is in the player, but the actual camera position when i press play, it's all the way back here (2nd pic)
Is your gizmo set to center or pivot
Set it to pivot and see where the camera actually is
for the camholder
for the camera
this is the code btw 1 for the mouseinput and 2 for the following of locking of the camera to a position
the cam holder is very far
NVM I GOT IT
Is your gizmo set to center or pivot?
Also, don't crop images so much
ty guys!
also do not multiply mouse by Time.deltaTime
What object has the MoveCamera script on it and what object did you set cameraPosition to
Still cropped too much. Why are you cutting the image off so much?
oh because i thought it was the only thing that was needed, but i fixed it!
the entire screen is always best
btw notice how you have to crank the sensitivity to 400 to work? remove Time.deltaTime on mouse, if you havent
sensitivity? yes.
im trying to check if between the script holder and the player, there is a wall object with the tag "Wall" - but it never returns true even if there is a wall. Any ideas what I did wrong? https://gdl.space/doquxoruze.cs
Use Debug.DrawRay
To see if it is going the direction you expect
It SHOULD be, but just in case
Also, debug the hits
myForcedLookTarget = transform.Find("DemoForceLookAt").gameObject.GetComponent<DemoForcePlayerLookAt>();
revealCurtain = transform.Find("DemoCutsceneStage/CurtainReveal").gameObject;
mySpeaker = transform.Find("DemoCutsceneStage").gameObject.GetComponent<AudioSource>();
I learned that finding objects this way is expensive. What other way is more efficient and lighter?
using components
Serialized References (drag and drop) or passing it from the instantiate call
or tags or ^
the issue is that there are so many of these script holders, I will end up with over 999+ debugs right after hitting play
Collapse the logs
nothing wrong with using Find once.. in a start / awake function to grab references
but using them in update (all the time) is really bad
Ah so okay. Thanks a lot for the answers
Incorrect. You should basically never use .Find. At least use something like FindObjectsOfType or FindWithTag so you aren't tying game functionality to the names of objects
oh
ya, strings suck
if u ever change a string w/o thinking about all ur code they're all gonna miss over the objects ur hunting
All right. Got it.
But drag in references whenever it is possible to do so. Faster, easier, less error-prone
nothing in console with this
Then either nothing is running this code, or the raycast hits nothing
how do i check if between two points, there is a gameobject with the tag "Wall"?
a raycast is a good way
I see you call IsWallBetween twice EVERY frame
Is there a reason for that?
LineCast actually would be better
i dont think so
got rid of the isWallBetween(); bit
(); x 2
any way to actually check for a specific object though? there will be a lot of objects in the way of the linecast between the player and the wall
use a layer mask
if u want u can use layers.. and a layermask
Do raycast instead of raycastall, and yeah, layermask to filter the potential objects that will be hit
so 1 raycast only detects walls
whenever me or my friends make a pull from our github (or checkout to a new branch, anything) we get the 'object reference not set to an instance of an object' error and need to assign the references over and over every single time
how can we make it so that they already come assigned?
Is the variable assigned in the scene?
yes, when we make the push its all cool and working, but then the other person has to start over
Did you save the scene and push the scene to version control
i think so? we saved the scene, we saved the code, commited and pushed and still wasnt there :[
And both the object you are referencing and whatever has AttackingRange on it are both in the scene to start, right? Neither one is spawned at runtime?
they both exist as objects/scripts from the start and none are spawned, if thats what youre asking
Then the reference should be saved alongside the scene. Did you enable Force Text for your asset serialization in your settings?
https://docs.unity3d.com/Manual/class-EditorManager.html
got it set as force text >:(
I have dungeons like this in my game. Basically such a map is a dungeon. Game = turn based.
There are tiles in dungeons where player meets enemy and battle scene is loaded. Game manager (singleton, as is also persistent in battles) returns player afterwards to the dungeon (if player weren't killed in turn- based battle). But...
Any suggestions on how do I keep track of which enemies were destroyed already and which chests were opened? Basically best approach to store the progress?
I intend to use json at this point if that's the way. Do I store all the tile information and then when player re-enters the dungeon instantiate the information from the tiles that weren't cleared yet?
- Give each thing a unique ID at design time somehow (UUIDs are an option)
- In your save file you can keep a list of already killed enemies and already looted chests (using their unique id)
- When you load the game, check each spawned thing's ID against those lists and do what you need to do (destroy them, make them already looted, etc)
**each **tile you mean?
Oh yeah... that makes better sense to destroy / disable / etc already looted ones rather than instantiate all those that aren't 😄
Maybe? Empty tiles might not need one.
some tiles that look empty will have hidden traps and something liek that I think... so yeah, but anyways, empty ones are whatever indeed
is there a better way to make these stairs walkable, i keep having to press A and D to get it to work and i get stuck at the top
A simple component like this might do the trick @visual hedge
public class GridItem : MonoBehaviour {
[SerializeField, HideInInspector]
private string _uuid = "";
public string Uuid => _uuid;
private void EnsureUuid() => if (_uuid == null || _uuid == "") _uuid = Guid.NewGuid().ToString();
void OnValidate() {
EnsureUuid();
}
void Reset() {
EnsureUuid();
}
}```
really depends on your player movement code
daaang all those lambdas (...
you don't need to use any lambdas - I just wrote it quickly in Discord
yeah, I will look into it, thank you 🙂 LEt me compute the thing you wrote 🙂
use ramps as colliders 😉
They seem to be using box colliders
unless there's another collider they're not showing
Hey, I'm making a platformer, and I wanna make a custom script for collisions because I don't think the default one can do what I want.
Basically, I want the player to not collide with a platform if it is hidden behind another object, if the platform is partially hidden, I still want the player to collide with the part that is visible but not with the hidden part
thers no code handling walkin up and down stairs.. rigidbody's dont do those too well unless suplemented w/ code to traverse them
Anyone knows if its a good idea to implement a character roaster with scriptable objects?
I have an "Entity Info" scriptable object for each character in my game
it's been pretty nice
It does feel slightly weird for EntityInfo to reference the Entity and for the Entity to refer back to its own EntityInfo
I store things like "name" and "description" in the EntityInfo
so the Entity has to know about its EntityInfo so that it can tell you what its name is
Many why you gotta roast em they're doing their best
🔥
bro thats hard
get one of those costco chicken ovens
Yeah just joking about the typo, ignore me
whats a good way to do enemy spawning restrictions in 2d? i dont want the enemies to spawn too close/on the player, but also i dont want them too far away
depends how many you are spawning
but usually you can get away with some sphere casting or distance checks
you have some structure to know where you can spawn enemies?
just came to my mind: Using UUID is quite overkill because the grid system I am using kinda assigns unique ID to each tile already and is expressed in Vector3int... plus the whole plugin comes with some tools to find desired tiles.
So might just use their Vector3int instead 🙂 But anyway, idea is clear.
as long as the enemies don't move!
Then you can use that yes.
they don't. Each "scenario" is bound to the tile and they don't move. Only player moves
you just need some kind of unique identifier
you might want to think about things like "what happens if I update the game and move the chest?"
A UUID could solve that problem, the V3I solution doesn't. But that might not matter to you
yeap. I was thinking about using scriptable object to hold the information about the tile, but I am not so sure about that now... I mean there's very elegant ways to do so and not so elegant... and I gues I will have to take the simpliest one for now 🙂
you'dhave a serializable container with the grid id and item id
yeah its much simpler to use unique id for serialization than to try to bind tile position to object that could have moved, or tile can have many, or object could not even be there anymore and so on
yeah, I was thinking about that indeed. There must be flexible and re-usable system... will give it a good thinking now. Thank you for suggestions
My goal is to select the text in the DisplayDifficultyLabel object, and modify the text. I believe what I have to do is get all the components in the children, that are specifically the text type, and store them in an array. If I can do this part, then I can probably figure out the rest.
I have tried the following:
var foo = GameObject.Find("GameOverMenu").GetComponentsInChildren<Text>();
var foo = GameObject.Find("GameOverMenu").GetComponentsInChildren<TextMesh>();
Both of these gives me an empty array.
Just reference the thing you need directly.
Or are you generating these difficulty labels things at runtime?
if I want to perform a dodge should I use a bool or disable the collider??
So maybe var foo = GameObject.Find("DisplayDifficultyLabel").GetComponentInChildren<Text>(); ?
no, just add a List<Text> field and drag the things you need into it
also, if you're using TextMeshPro, you have the wrong type
Text is the legacy Unity UI text
I am, so is that TextMesh?
The correct type is TMP_Text
which covers both TextMeshPro (non-UI) and TextMeshProUGUI (UI) text components
its best to do what Fen says, but the problem seems to be either you are starting the Find from the object that doesnt have direct child "DisplayDifficultyLabel" or, the objects are disabled when GetComp is called and you are not using the overload of it that includes inactive children
or the legacy text thing yup
or should I change the layer of the object?
I did this in combination with using TMP_Text and I'm able to change the text now. Thanks!
soo dpi cant be read by unity software?
Different solutions work on different things. For example if you disable the collider and are using rigidbody movement, you are falling through the floor. If you rely on the layer for other things, which you want to still function during this time, then changing the layer wont work either.
oh okay, so the best day would be a boolean right?
🤷♂️ maybe. I wouldnt say it's the best because something suddenly has to check this bool. If you have a rigidbody projectile, your bool will have 0 effect on the object and it will still collide with your player even if it doesnt damage them. I think layers could work fine because you can do layer based collision
It all depends on your system
hmm I see, so maybe changing the Layer of the object should be more precise?
As long as you are aware that the characters can live in different layers while coding other features, sure
Can someone help me with a plugin quick
Assets\Scripts\PlayerMovement.cs(17,5): error CS0246: The type or namespace name 'RigidBody' could not be found (are you missing a using directive or an assembly reference?)
RigidBody rb;
hello i have like kind of a problem with my movement when i am moving everything is fine but when i try to sprint its like stuttering could this be because of the sprint function being in the fixedupdate?
is what i typed
yeah i think so
okay thx
yo what plugins you using for unity
wdym
Rigidbody not RigidBody
!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
thanks
Your IDE is not configured if it didn't suggest the correction for you btw
It could be, are you using rigidbody movement? Show code
Also it depends on how the camera is moving. Its possible your character isnt stuttering at all, but that your character and camera arent updating at the same time
what is the link to put code snipet in here
and yes i am using rb movement
!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.
would it help to just put everything in update?
how can I make a layer not to collide with specific layers?
