#💻┃code-beginner
1 messages · Page 635 of 1
So grounded would always be false if you check it between the two
You should use one call so grounded is accurate whenever you check it
oooh yes i can see, now that i have 1 move function it works
how do i apply gravity then? do i add a vector3 in the move function for movement and then on the y axis i add the gravity?
aah yes found it guys, thank u all!
oh, well, thanks :3
emmm then is there in unity that calculate the distance between two object??
I downloaded unity and i just noticed my unity is in low quality how can i fix that?
are you tallking about the Game View ?
or the Player Quality
also not a code question #💻┃unity-talk
you cropped out the Zoom amount in the GameView
the player quality and gameview
wdym?
1920 X ?
1080
can you like show the Scale number?
this is what i have
public class RuinStoneScript : MonoBehaviour
{
public string interactionKey = "e";
private bool isInteracted = false;
private Renderer stoneRenderer;
private MaterialPropertyBlock propertyBlock;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
stoneRenderer = GetComponent<Renderer>();
propertyBlock = new MaterialPropertyBlock();
}
// Update is called once per frame
void Update()
{
if (isInteracted == false && Input.GetKeyDown(interactionKey))
{
Interact();
}
}
private void Interact()
{
// Ensure the emission color is green when interacted
Debug.Log("Interacting with " + gameObject.name);
// Get the current material properties
stoneRenderer.GetPropertyBlock(propertyBlock);
// Enable the DECAL EMISSION (assuming this is controlling the emission effect)
stoneRenderer.material.EnableKeyword("_DECALEMISSIONONOFF");
// Set the emission color to green
propertyBlock.SetColor("_DecalEmissionColor", Color.green);
// Apply the property block changes
stoneRenderer.SetPropertyBlock(propertyBlock);
Debug.Log("Emission should now be green for " + gameObject.name);
isInteracted = true;
}
void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
Debug.Log("Press 'E' to interact with " + gameObject.name);
}
}
}```
I havent mentioned anything about resolutions
agh use a Link its hard to view a wall of code on discord 👇
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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 can't zoom out anymore
you have to select the dropdown and uncheck the Low Rez Aspect Ratios
https://paste.mod.gg/ebgdcsziytgz/0 like this?
A tool for sharing your source code with the world!
so this is a custom shader / material ? where did you get the properties names from
general Color.color isn't enough you typically need Color * Intensity no ?
thanks how does it look now?
yeah when i click on the edit material, it brings me here
i think thats his custom shader
now you're zoomed out, if you want to keep it at 1x without worrying about zoom use the Aspect Ratio 16:9
ty
Vector2/3.Distance
are you only ever going to change it green ?
also DecakEmissionColor 
Is it better start learning programming with “beginner scripting” or “unity learn essentials programming pathways”?
both
wouldn't hurt would it
the pathways just kinda ease you into the same topics
Which one first? I’m getting mad for the first tutorials of loops, I read comments that says they are not explaining good some things
Beginner Scriptingis where I started because pathways werent a thing.. its good but does require some very basics still.
the pathway is a bit clearer and more structured..
also the beginner scripting order is all over the place
yeah i want to make it so when its interacted with, the color changes to green to let the ppl know this object has been interacted with. (its default emission is blue) and the DecakEmissionColor, i didnt change anything there, i think its always like that
well if thats the name what you wrote is probably wrong lol
woldnt it be easier to just have 2 Materials ?
thats generally what i do, I swap them out so its easy
InteractedMaterial as a field / resource to replace it with
Hmm so it’s better to start with pathways and maybe I’ll return on beginner scripting (if it’s a good idea) thank you
im not sure, im new to this and its for my class. I originally had one texture which has the same symbol for the rock, i duplicated it a few times and changed each texture's symbol to something unique and assigned it to the rocks so all rocks have different symbols
yes def come back to it after the pathways, it still has good solid raw c# concepts combined with untiy. its just more crude than pathways..
As always very kind, thank you so much again
I deleted something and now it looks like this
Idk how to get the texture back
I did ctrl+ z
no work
magenta means you are using either no material or a material that is not compatible with your render pipeline
I got the files from the trash now its back tys
is there a way too move just the sprite of an object? (Whitout the collider)
Sprites have no position, it's the object itself that has the transform.
Make the sprite a child of your root object and offset its local position instead
Generally speaking, you want your "art" to be children of a root object anyway.
oh thanks never did that lmao
any opinions on text animator vs super text mesh vs alternatives? i'm kind of inclined to like the tag approach in ta but i'm hoping to hear from users
make your own for free
heyo, im working on making a scriptable object where i can make new heroes for my game. however, i want the affinity option to be a dropdown in the engine instead ofa script, how would I go about doing this? I tried making a lis tbut that didn't work
using UnityEngine;
[CreateAssetMenu(fileName = "NewHero", menuName = "Hero")]
public class Hero : ScriptableObject
{
public string Name;
public int HP;
public int MP;
public string affinity;
public Sprite artwork;
}
make affinity an enum
time to learn what an enum is :/
enum Season { Spring, Summer, Autumn, Winter };
it's basically just a list of predefined values
it's an association of labels to integer values at the lexer level
in that example above, Spring is 0
but you don't have to manage it
this gives C# a way to say "here are the specific permitted labels"
a type is created (in this case Season)
you then use that type on the field you're trying to expose in the editor, and the editor now knows what things are permitted too
using UnityEngine;
[CreateAssetMenu(fileName = "NewHero", menuName = "Hero")]
public class Hero : ScriptableObject
{
public string Name;
public int HP;
public int MP;
public enum affinity{
Earth,
Fire,
Water
}
public Sprite artwork;
}
this is what i tried(it doesn't work)
you have to define and use the enum separately
the enum goes outside the class
go look at an enum guide
you're going to end up calling that enum Element or something
then where you tried to put it, you write public Element myElementFieldNameGoesHere
think about it like it's actually a real type, in the way integers and strings and so on are
you're going to want to be able to use it more than once
that's not going to be the only place you use elements
and you don't want to have to repeat yourself, or make sure they're all the same
you'll want the elemental damage bonus on your sword, the elemental defense bonus on your shield, etc, etc
those should (presumably) all use the same concept of what an element actually is
i seee
enums, like structs and classes, are a way for you to create your own types
this is good for a bunch of reasons, but one of the big ones is when you teach c# how your data actually works, the compiler can start catching your mistakes for you
consider the season example i gave, above
if someone accidentally wrote "fall" instead of "autumn," the compiler can now catch it
whats a field name?
oh hell, i don't know what c# calls them. whatever the label is of the member method
Name, HP, MP, and artwork, above
well
i just tried this
using UnityEngine;
[CreateAssetMenu(fileName = "NewHero", menuName = "Hero")]
public enum affinity{
Earth,
Fire,
Water
}
public class Hero : ScriptableObject
{
public string Name;
public int HP;
public int MP;
public affinity Affinity;
public Sprite artwork;
}
public float health
"health" is the field name
Assets\Hero.cs(3,2): error CS0592: Attribute 'CreateAssetMenu' is not valid on this declaration type. It is only valid on 'class' declarations.
that line above the thing you wrote is part of the class
you shouldn't be splitting it off that way
merci
oh
sorry, i'm new to unity and c#, i'm occasionially going to use phrasing from other languages because i'm liquid dumbass concentrate
im new to unity and c#
i only really know java
and im not even a pro at that
it worked! thank u :3
I've checked out Super Text Mesh, but that was a long time ago. I didn't like it, and I actively use Text Animator now.
okay. do you happen to remember what you disliked?
I don't, this was before TA existed.
But I do remember appreciating that TA literally sat on top of a TMPRO component.
is that about being a standard interface and being easy to integrate, or something?
You don't have to do anything other than add the text animator to an existing text mesh pro object and you're done.
i kind of feel like i can just make a tag for each alien species, and i'll get uniformly styled text fairly conveniently. is that sane?
like, it's not d&d, but that's a sufficiently universal metaphor, so, goblins would get bold green text, vampires would get dark red text in a halloween bleeding font, ghosts would get 75% alpha text in a sketch font, &c &c &c
Yep, you can easily make your own tags like that.
@noble cedar - something isn't cleaning up behind itself
Not enough context really other than something is allocating something in the jobs system with Allocator.Temp/TempJob and it's living longer than allowed
is there any way to check what that thing is?
reading the full stack trace would be a good start
@frosty hound - any chance you also have opinions about Pixel Crushers dialog system?
I haven't used it, but I know it's always a recommended solution. It's been used successfully in successful games.
sorry I am dumb what is stack trace?
in an error message it's the list of code lines on which the rror took place
I just mean look at the full error message
yeah see all that, that';s a stack trace
it's a trace of the program execution stack
basically just - which function is currently calling which function, etc...
anyway looks like it's netcode related
ahhh good to know 😄 that will save some time finding where that bug is from
so I f up somewhere in installing netcode?
I didn't say that
just that the issue is somehow netcode related
it's not necessarily an error in your code
it could be a bug in the netcode library itself
yeah the field name
oh i wasn't scrolled down sorry
Man, text animator looks like something you can make in one sitting. Maybe I'll make some trashy version and put it up on git
already hate multiplayer LOL
multiplayer is a classically challenging problem
do people really pay for someone to throw on some sin waves on text mesh pro and add a parser to it all
it's probably not well suited for your first game
it's not for the faint of heart
@timber tide - yes, I will pay $65 to save myself three hours.
I have been doing it for past 300h with no good progress
that's not far off CA minimum wage
Yeah true. Maybe I'll make a budget version then lmao
Did someone tell you it was easy? It's not easy and anyone who said it was lied
my teacher said that it would be easy :/
@noble cedar - are you using a library or doing it from scratch or what
I am confused by your question what do you want to know
like are you setting up some library you found in unity store
something like coherence or normcore or nakama or whatever
or are you actually opening sockets up
unity multiplayer center?
I downloaded from there netcode for game objects
when I asked him he said he never did multiplayer in his life and though it was easy
yeah it's generally one of the most difficult things to do in gaming except in turn based stuff
like, it's not too bad for like chess and whatever
but for regular games, it's a hard problem. the network isn't instant and coping with that is strange.
if you knew how much dark magic netcode was burying for you, etc, etc
we are back to dark magic damn
it's a common metaphor
Unity's solution is pretty simple. You can just do server authoritive approach and funnel everything into the server, and only client-side the camera. Otherwise all the synchronization is pretty straight forward to set up
anyway, look, there's one other way to look at this: you've managed to put 300h into a project and stuck to it
that's the actual thing that makes a programmer
fortitude
so you're doing something right
I have been working on it for past 3months so yea could be correct
if you've done five days a week for a little under four hours a day, you're there.
so again is there way to check total time spent in project?
i don't believe unity times you.
aww man sad anyways I am going to sleep
ill sync shooting tmr I am happy I synced movement now xD
how do i make weapon recoil it keeps glitching out
gonna need a lot more detail than that
first time i did it it kept shaking camera even if i stopped
now i separated it from gun script
and it goes left and up
and rotates around
if u put intensity to high
if not this is what u get
and now it doesnt even work
using UnityEngine;
public class ProceduralRecoil : MonoBehaviour
{
public Transform cameraTransform;
public float recoilX = -3f; // Vertical recoil
public float recoilY = 2f; // Horizontal recoil
public float recoilZ = -1f; // Pushback effect
public float snappiness = 15f; // How fast the recoil applies
public float returnSpeed = 6f; // How fast it returns to normal
private Quaternion originalRotation;
private Vector3 originalPosition;
private Vector3 targetPosition;
private Quaternion targetRotation;
void Start()
{
originalRotation = cameraTransform.localRotation;
originalPosition = cameraTransform.localPosition;
targetRotation = originalRotation;
targetPosition = originalPosition;
}
void Update()
{
// Smoothly transition to recoil rotation and position
cameraTransform.localRotation = Quaternion.Slerp(cameraTransform.localRotation, targetRotation, Time.deltaTime * snappiness);
cameraTransform.localPosition = Vector3.Lerp(cameraTransform.localPosition, targetPosition, Time.deltaTime * snappiness);
// Gradually return to original rotation and position
targetRotation = Quaternion.Slerp(targetRotation, originalRotation, Time.deltaTime * returnSpeed);
targetPosition = Vector3.Lerp(targetPosition, originalPosition, Time.deltaTime * returnSpeed);
}
public void Recoil()
{
float recoilUp = Random.Range(recoilX * 0.8f, recoilX * 1.2f);
float recoilSide = Random.Range(-recoilY, recoilY);
targetRotation *= Quaternion.Euler(recoilUp, recoilSide, 0);
targetPosition += new Vector3(0, 0, recoilZ); // Push camera slightly backward
}
}
``` this is last script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ProceduralRecoil : MonoBehaviour
{
Vector3 currentRotation, targetRotation, initialGunPosition;
Quaternion baseGunRotation;
public Transform cam; // Camera reference
[SerializeField] float recoilX = 1.5f;
[SerializeField] float recoilY = 1f;
[SerializeField] float recoilZ = 0.5f;
[SerializeField] float kickBackZ = 0.05f;
public float snappiness = 10f;
public float returnAmount = 15f;
private bool isRecoiling = false;
void Start()
{
initialGunPosition = transform.localPosition;
baseGunRotation = Quaternion.Euler(0, 90, 0); // Base rotation of the gun
}
void Update()
{
if (isRecoiling)
{
// Reset gun rotation
targetRotation = Vector3.Lerp(targetRotation, Vector3.zero, Time.deltaTime * returnAmount);
currentRotation = Vector3.Slerp(currentRotation, targetRotation, Time.fixedDeltaTime * snappiness);
transform.localRotation = baseGunRotation * Quaternion.Euler(currentRotation);
Back();
}
}
public void Recoil()
{
// Apply recoil effects
targetRotation += new Vector3(
-Mathf.Clamp(recoilX, 0, 2),
Random.Range(-recoilY, recoilY),
Random.Range(-recoilZ, recoilZ)
);
// Apply backward kick
isRecoiling = true;
}
void Back()
{
// Smoothly return the gun to its original position
if (Vector3.Distance(transform.localPosition, initialGunPosition) > 0.01f)
{
transform.localPosition = Vector3.Lerp(transform.localPosition, initialGunPosition, Time.deltaTime * returnAmount);
}
else
{
isRecoiling = false;
}
}
}
btw it'd be much easier if you posted links than a wall of text, its harder to read in discord especially if you have to keep scrolling to view previous messages
i didnt consider it long
an entire class usually is
it takes up 2 screens worth of space..
usually the inline code is more for like a couple lines
then you should consider making things easier for others to read?
You literally had to split it into two messages
its 2 different scripts
2 version
with the same name?
version
okay.. even more reason to use links, esp one that allows multiple tabs each script
so what can i do from here im using this script i replied to
it does weird twisting
whats twisting ?
videos would help better visualize the problem
generally you dont want to AddRecoil to the same object as the Camera.. Since usually 1 script is rotating the camera you will have fighting over the rotation/transform
usually a parent container is used
its shown in picture it points to right corner and stuff its not a normal position
unlike csgo cod and other games its very unrealistic
yes
not in this case
because camera doesnt move
when i shoot
You dont have rotation code for camera fps?
Why are you using fixedDeltaTime in one of the slerps?
Idk it just doesn't move with that script
Whats wrong with it
yes not that script but another script, they could be fighting rotation with each other if its the same object.. or worse like gimbal lock , probably not case here but still
That script does nothing
Why did you choose to use it
I asked Bing ai to help me make it
Yeah, thats the answer I was fishing for
Nothing is wrong with it tho
if that were the case then you wouldn't be here trying to get help with it
Don’t post unverified AI-generated responses in questions or answers; check for accuracy, and state what’s AI-generated.
We are tired of people coming in here with low effort AI crap
And not even disclosing that AI was used
There where no tutorials
Nobody helps me when I say it
For recoil?
The internet is riddled with FPS recoil tutorials
And I didn't know that rule either
Yes
because nobody wants to help you with code you don't even understand
What else can I do
I did w3schools tutorial
stop generating AI Slop and go learn what you are trying to do instead
How
I didn't find good tutorial
All I know is how to make basic thing like csgo 1
But not like cod
no, you didn't find a tutorial that did every little thing for you. you found plenty of tutorials that teach the general concepts you need to know, you just won't use them and put that knowledge together.
I did that
But I don't know how it's supposed to work
no you didn't, you used a bullshit generator to generate bullshit for you instead of learning the concepts
I know the concept
then use that knowledge and make your own attempt at implementing recoil and maybe you'll get more help
But it doesn't come out realistic
It comes out what I put
Instead of random
Recoil
I am new to unity, trying to use a region as material sprite from texture2d but my texture comes out weird, I even set the right UV offsets etc.
I see sry is there a channel for editor questions? do you know the answer ?
isn't it this channel?
that is a link to a specific message
I see
did you read this part
Thanks, I managed to do it. The problem was that the authentication method used by this old version of MySQL Connector was different, and then utf8mb4 was not supported. I changed the authentication method in MySQL, and set it to utf8.
Thank you very much.
Hi so im trying to remake pong and the ball bounces on the bounds but when It makes contact with one of the players (the paddle things) its just phases right through them. Why is that?
you'd have to show your setup, we don't see anything related to your game.
well guess i shouldve been specific, !code on how to share code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
also you can follow through the steps here https://unity.huh.how/physics-messages to see why you might not be getting a collision
also how are you moving the player paddle ?
its also possible your paddle went to Sleep
I would keep Sleeping mode to Never Sleep
(on the rigidbody2d)
??? why and the player is assigned
whats on line 15 ?
if its assigned for a fact (eg you checked the inspector and its fine at runtime)
consider checking if there are multiple of same Scripts, with one of the fields not assigned
Thanks I fixed it
It was actually not fine lol
It wasn't going through earlier why now?
the collider is smaller than the visuals
how so
idk I'm going by the image, did you resize the mesh without resizing the collider?
Yep your correct i was messing with the part's property and i saw that you can customize the collision size and postion
ty
is there a way to make the collider match the size?
set collider size same size as cube scale
like always and automatic
only if they are on the same object
wont work i already tried it
assuming your cube doesnt have any parent that is scaled bigger / smaller
works fine look
assuming they have parent whos scale stays at 1,1,1
otherwise it won't be exact and you have to take parent scale into account
Ty. one more thing how do i wait in c++ for a certain time
default Unit is 1m
we use c# not c++
I thought it was c++ lol
nah the Engine itself is written in c++
we interact with the API thats in c#
make a delay using Update w/Time.delta or Time.time, or Coroutine
I used it, its pretty easy unlike c# I guess it was meant for kids
isnt it basically LUA ?
I used LUA to make gmod assets / mods. It was not fun
c# is easy
Luau
just takes a bit of time getting used it, you'll be wondering why you ever touch something like lua
Luau and lua the same?
Luau is a flavor of lua , heavily modified
roblox studio is like Unity but bad at the same time good
roblox studio doesn't have the graphic unity has
Can you make values and save them data stores?
Nvm almost everything is possible so prob yea
everything is possible
default answer to "is it possible xyz"
Hey Im following a tutorial, but I dont understand one thing if he enters the scene and switch to his lvl scene the player appears out of now where how? when I do this my player dont appear
In this video we begin by building a small play test arena. After, we add Unity's Input system to our project. We then learn how to set up inputs using our newly created input functionality. We end by creating some player classes which will be used to begin controlling our player character.
► GET MY GAME ON STEAM
https://store.steampowered.co...
min 17:40 the player cloned but I dont undertand how can maybe someone explain please?
What is player in the first scene and are you tagging it as dont destroy on load
Or better question, how are you making a player in the next scene
this is my question in the video he don´t have the player in the first Scene and in the second but when he start the "Game" and goes to the Second Scene the Player appears and I dont understand how
Then add the player prefab to the next scene?
How come I'm not finding the rendering mode on material i wanna make it transparent
I'm noticing that 2d collider stuff stops working when I use a perspective camera on an angle instead of top down. Is there a workaround for this?
It depends on the material(shader to be precise)
omg is that AI?
when I do this my Camera isnt following my player like the one from the tutorial
https://pastecord.com/juzygihyqy.cs
google's AI Overview
yea google
shiiiiet
lol
Anyway it didnt tell you , switch the Surface type to Transparent instead of Opaque
To be fair, the ai is not wrong. It just doesn't tell the whole story.
The issue is that people relying on it too much, stop thinking with their own head.
yeah thats what sucks, it just either completely wrong or incomplete
(big problem when you dont know the answer given to you is such a thing)
Bro what am i supposed to do i have no knowledge and i don't want to ask common questions in the server its just relaying too much on people lol
That's the point where you go through beginner courses or read the manual. !learn.
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
also confirm the correct answers usually from the unity answers site / stackoverflow
If you do intend on using ai, make sure you ask the right questions, clarify ambiguous info and confirm it in the docs or on practice.
You have a property that requires a player on the camera, but you dont have that info until the player spawns in the next scene. You need to either have the camera look for the player on the scene, or have the player find the camera and insert its reference into it. I would probably make a camera class singleton and just have the player communicate with it when it is created.
Nice game you made dude
imo if you have no foundation for coding you shouldn't use AI at all or you'll cripple yourself.
Ai helps but you need to learn first
Thank you so much
main problem comes with over reliance too and especially taken at face value without doubts
Does unity have tweening?
coroutines, or just lerp inside of update
the animator tweens I guess too yeah
no way thats cool so i can animate parts
otherwise there's a bunch of plugins out there
Interesting
Another idea is just destroy the first scene camera such that you make it again in the next scene. That would require removing the DontDestroyOnLoad tag from the first scene camera.
There’s a lean tween package you can get off the asset store with all the libraries for different tween curves
They are pretty cool and can be used for a lot of things
cool can't wait to try them out!
hey, I was asking for help earlier on how to set up an enum. now im wondering if there is a way to set up a table similar to that of the sort? I don't know how to explain it other than what the concept is that I'm going for.
Ice: Weak
Earth: Resist```
time to learn dictionaries
basically allows you to make some value type (and references!) point to another
and quickly to access
i found a youtube video explaining
thank you for pointing me in th eright direction
🙂
so i could do
Dictionary<affinity, reaction> affinityRelations = new();```
or something of the sort
Dictionary<affinity, affinity>
If you want to use the same enum
possibly Dictionary<type, float> would be best. You could use 1 for normal, 2 for weak, .5 for resist, or even use other values as needed
question: how would two affinities work for key and value?
Like can do
Key = Fire, Value (what is weak against) = Water
Also a possibility^ and then you would have 1 dictionary for weaknesses and 1 for resistances
ohh
(assuming they're asymmetrical like Pokemon)
there are many ways you could do this, depending on your needs.
something along these lines
No idea what I'm looking at here lmao
if youa ttack with ffire onto this monster, it repels
but im not adding repels, just hte best example i could think of (persona 5)
If it has multiple weaknesses then you do something like
Dictionary<Affinity, List<Affinity>>
in this case you could do something like:
HashSet<Affinity> resistances and HashSet<Affinity> weakneses if it's tied to a particular monster not a particular type
this is what i was looking for
i didn't know how toe xplain
its by monster not type
thank you
(what is HashSet)
what's rpl vs str?
hashset is dictionary lite
HashSet is a data type that is optimized for Contains, Add, and Remove checks
and cannot have duplicates
i see
it's faster than List for those operations
repel and strong(against)
Yeah, if you don't care about ordering of elements. Always go for hashset
which most people don't realize how good of a data struct it is with c#
main issue with it is it's not serializable in Unity
so it's something you have to build at runtime
(possibly from a serializable list or array)
im not sure if thats aproblem
oh yeah that's true
but in this case if you do want to use dictionaries, you'd probably be just hardcoding the values
otherwise need to make a struct middle man to serialize in the editor -> then create dictionary at runtime
Weakness types and stuff like this isn't likely to change anyway
No GameManger??
did you spell it right?
It's not a built in type in Unity, if you didn't make one, there isn't one.
Oh, how do i make one
hey, i've already asked this question in VR, but i figured it might be better here for visibiity.
im trying to make a multiplayer passthrough XR app. I'm like 90% done with a template, but im facing an issue where my 'Building Block] Networked Avatar is spawning, but isn't following the xr rig. Has anyone had this issue?
you make a script called GameManager and that's your GameManager class
the question is why are you trying to use such a thing if you didn't already make it? You seem confused about something.
If you're following a tutorial you'll need to follow the part where they make the GameManager script.
Thanks I thought it was built in
The guy on the tutorial didn't show him creating the script so i got confused lol
you either skipped it or it's just a bad tutorial
or maybe they will get to it later
He has almost 2m subscribers lol
that doesn't mean shit lol
youtubers are entertainers
most youtube tutorials are bad, including the popular ones
maybe especially the popular ones
Watching this guy named Brackeys
if I didn't had experience using roblox studio then I don't think I would have lasted the first 2 tutorials
The problem also of not following a structured path
Jumping from yt to yt won't work well
!learn 👇
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
All flare and shit substance for new comers
I feel like I've got something out of his stuff from way back when
So much YouTube content feels like it's useful to beginners but secretly isn't
He's a good presenter and for specific things it's helpful but his code usually is all over the place
Much eaiser when you can recognize where its kinda bad and improve upon it
I see a fair few people make the mistake of thinking sebastian lagues videos are tutorials, then get very frustrated when they can't get his source code to do what they want
Which is damn hard for beginners, it's a shame
Yup that's the problem , believe me I was there lol
hey has anyone here had experience making things for meta xr headsets?
Also YouTube is an entertainment game, for a unity tutorial series to actually provide highly useful and informative content, it'll be the most boring thing for beginners
The best tutorials I've ever seen are various Unity ones, as those do one thing I've barely seen anyone do. Actually explain why it is they do certain things
I make a video whenever I struggled with something and want to show others that might need it how I did it..I'm not in it for the follows or view
If something is wrong or confusing I delete it
In one he renamed something and then explained that name was totally arbitrary with no impact on the code.
I don't think I've ever seen anyone do that
Also he made gradual changes to the code and stopped halfway through to summarise, before moving on
Like mass rename all places w that variable ?
And yeah variables names are irrelevant they're just for you
I think it was just a new name he gave to something and the name could have seemed important
It all gets made into machine code
I'll try and find the video
Hi, I'm new to Unity. What is the correct set up for two parts of a player to rotate independently, but use the same physics-based movement? I could give them an empty parent with a Rigidbody for physics based movement, but if it gets rotated then it will affect both children. So do I use a Rb for the child objects? But then, they won't have the same position... shits confusing.
you probably need to elaborate more on what kind of independent rotation you're talking about
what's the gameplay thing you're trying to accomplish
I just mean have entirely different code that controls the rotation of each part
but in what way
One is movement based, one is mouse based
It just sounds like you would have a RIgidbody parent and then rotate these children via code
Using transform?
sure
is there any reason they need more than that?
are they.. gun turrets?
Or what
Yeah tank hull + turret
lost to time 😔
the tank hull doesn't need anything special, it's just the RB or a child.
The turret you'd just rotate via its Transform.
Anybody know why this isnt working. Im new and trying to learn how to script so forgive me if the answer is obvious. Im trying to use this player movement script to be able preserve momentum and allow adjusting midair for platforming. However whenever i test in game i only move along the y axis when jumping.
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
didnt realize as im on pc ill fix rq
I honestly could rant for hours with how much is wrong with the state of online gamedev "tutorials" 
My book will be called "the illusion of learning"
So, the hull should inherit the parent's RB rotation, and that won't affect the turret as it's modified using transform.. or will the turret's transform be affected by the RB rotation?
the hull should inherit the parent's RB rotation
You say that like you have to do something extra to make this happen
that's the default behavior
will the turret's transform be affected by the RB rotation?
Yes but since we're going to update it manually via script in Update it doesn't matter
we will overwrite that
here it is
i only move along the y axis when jumping.
To be clear what are you saying here? That you lose all horizontal momentum when you jump?
yes If i jump and try to move or am already moving, my character will not have any horizontal momentum, only vertical
Well this part is weird:
moveDirection.x = Mathf.Lerp(moveDirection.x, right.x * targetSpeedX, airControlFactor);
moveDirection.z = Mathf.Lerp(moveDirection.z, forward.z * targetSpeedZ, airControlFactor);```
can you try commenting that part out entirely for a moment
I don't think that code is correct - it doesn't really account for the character's rotation properly
Maybe I did something wrong then, because originally I had the hull as the parent with a Rb that gets rotated by script, and the turret as the child with a script that sets transform.rotation in Update(), however I found that rotating the RB had a small effect on the rotation of the turret, when it shouldn't.
Is setting transform.rotation = in Update() wrong?
I mean it kind of depends on the exact nature of your code.
if you were not instantly setting the rotation to exactly aim at the mouse, then yes there will be some visible effect from the rotation of the tank body
i.e. if you were doing some kind of interpolation or movement over time
not inherently but details matter
Yeah that's what I thought, but it would permanently aim slightly off from the mouse due to the Rb's rotation.
Not briefly
Since the transform of the turret is modified very quickly in update, I wasn't sure how this was happening
That really depends on your code
you'd have to show it
That sections was supposed to allow me to adjest the character speed while jumping, so i can slow down mid air. But your right that is causing the bug. Ill try to find another way to implement
Code for which object?
Yeah it's just... not correct. I think you would want
Vector3 desiredMoveDirection = (forward * targetSpeedZ) + (right * targetSpeedX);
moveDirection.x = Mathf.MoveTowards(moveDirection.x, desiredMoveDirection.x, airControlFactor * Time.deltaTime);
moveDirection.z = Mathf.MoveTowards(moveDirection.z, desiredMoveDirection.z, airControlFactor * Time.deltaTime);```
and probably set airControlFactor a lot higher than 0.05
Oh I found the cause but am not certain of why it happens. With the hull and turret as children of the empty object with position and rotation set, it works fine. The turret's rotation overrides the Rb rotation perfectly. However, if I set the turret as a parent of the hull (which is still a parent of the empty object) moving offsets the turret's rotation.
I was thinking it's a physics issue, but the hull object in this case literally has nothing attached apart from a mesh renderer so I don't understand why this happens.
why would the turret be the parent of the hull?
that seems backwards
I don't know if I'm convinced.
The hull has no scripts running. It inherits everything from the empty parent. When they are both children of the empty one with all the movement logic, I have no issues. Same code, but just changing the hierarchy to empty > hull > turret causes this issue.
If you switch to LateUpdate I wonder if it changes anything? It might be some niche update order issue.
(for the turret rotation code)
No difference with that
Very weird. I mean I guess there's no difference if I have them both as children, it's just odd not knowing why this is happening.
It's been a while since I did animation stuff.. I want to edit some animations but now it seems I can't edit any animations that I have..
I want to add a property but it's locked up.
if this animatiuon is imported from an fbx file you can't modify it directly
you have to duplicate it and modify the duplicate
Ok I copy pasted it but still can't add property
oh right
bug: Hello, heres a script a I have on the parent of a weapon gameobject. It makes the weapon sway but the problem is that its super choppy. Sometimes when I click play its smooth and other times Its laggy or choppy. Any ideas?
https://pastecode.io/s/ewhto8w9
How can I set a 2D collider to only apply collision with non-transparent pixel?
anyone have a good tutorial that shows how to use scriptable objects
colliders don't care about pixels
only other colliders
I tried adding custom physics shapes:
chat gpt is telling me to use polygone collider but it didnt work
those are only important for tilemap colliders
polygon colliders work just fine.
so I added polygone collider to my tilewalls (the tile shown on the picture above) and I tested it, I am not colliding with them.
So now im having the issue where when im crouched by the edge of a platform and uncrouch, I get kicked off of it. Im assuming that its because since when i crouch my entire player object including the collider and capsule get transformed down, that my colliders clip the floor and it kicks me off. To fix this would I have to dynamically change my colliders on crouch?
Are you using tilemap or no
yes I am
then no you wouldn't use anything except the TilemapCollider
from this screenshot it's not clear what custom physics shape you've defined
just looks like a plan square
Ok and... Do you have a tilemap Collider on your tilemap?
yes when I use tilemap collider, its not respecting the physics shape as collider.
Anyone know why isGrounded is logging true & false at the same time when grounded?
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
private CharacterController controller;
private Animator animator;
private Vector3 velocity;
private bool grounded;
public float speed = 5f;
public float jumpForce = 1f;
public float gravity = -9f;
void Awake()
{
controller = GetComponent<CharacterController>();
animator = GetComponent<Animator>();
}
void Update()
{
grounded = controller.isGrounded;
if (grounded && velocity.y < 0)
{
velocity.y = -0.1f;
}
Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0);
move *= speed;
if (move != Vector3.zero)
{
gameObject.transform.forward = move.normalized;
}
if (Input.GetButtonDown("Jump") && grounded)
{
velocity.y += Mathf.Sqrt(jumpForce * -2f * gravity);
}
velocity.y += gravity * Time.deltaTime;
Vector3 totalMovement = (move + velocity) * Time.deltaTime;
controller.Move(totalMovement);
HandleAnimation(move);
}
void HandleAnimation(Vector3 move)
{
if (move != Vector3.zero)
{
animator.Play("Walk");
}
else
{
animator.Play("Idle");
}
}
}
it seems to work fine. Maybe the collider is too small for my player or maybe the player collider is too large.
Also this is all not a code issue
It isn't.
In fact it's not logging anything based on this code
Sorry, i removed the debug part it was just Debug.Log(grounded);
Either:
- it's alternating each frame
- you have two instances of this script in the scene. One of which is grounded, one of which is not
How could i fix alternating?
I would strongly suggest not using CharacterController.isGrounded. It's very finicky.
Thanks! Should i use raycasts then?
something like that
so why is the player controller thing messsed up like this i cant figure it out and im a dumbass pls help d;
if i edit the height, its below the player?
remove this
And set this to Pivot mode
@wintry quarry Thank you, I did that but it seems like its the same issue. Basically im trying to fix this because on game start the character is spawning above the floor. I think its because of the player controller but editing the height it still is underneath the character.
what is underneath the character
your description is not clear
show your hierarchy
and what components are on each object
see how the player controller is underneath the character
i cant seem to get that to fit AROUND the character
You seem to have extra colliders or something
on the child object(s)
delete them
these two are just the capsule and cube that create the front facing of the character
show the capsule
what components are on it
show its inspector
I see i see
its at 1 because thats the position it needs to be to be above the plane, if not its going to be on the same level as the plane, aka inside
ok
then it's fine as is
if things look alright visually
I think your problem was just the extra capsule collider
the box should also not have a collider btw
Basically CharacterController gets very finicky if there are any extra colliders
CharacterController itself is already a capsule-shaped collider
pretty sure there isnt any problems as long as you keep pushing the controller downwards even when he is on the ground
is it normal if i made an interface class but does not extend it or inherit it at all
but instancing it by doing
private IDialogSteps dialogStepSystem;```
I have a SpawnManager game object w/ a SpawnManager script and some empty game objects to represent spawn points for both player and enemies. The player and enemies are prefabs that I spawn on Awake() of the SpawnManager script. It seems like my enemy is walking towards position.x of 0. My EnemyMovement script uses the player's position to drive its direction. Everything appears to be connected properly in the Unity editor. Here's a video of what I'm seeing. I can provide code snippets if that helps.
Anyone have good resources on setting up a character movement system that doesn't rely on a capsule collision (instead using a mesh collision?)
Or explanation
This isn't instancing anything
you made a variable
also it's just an interface
not an "interface class"
what kind of character controller , also is there specific reason for mesh collision?
Any way of getting rid of "reference not set to the instance of a object" error? I dont know if what im showing is enough and i will show the rest of my script if needed
which line ?
line under OnEnable()
then you cannot find the object by that name, its not finding. You cant access GetComponent on a null
Set your reference to an instance of an object.
Also you need to configure your IDE.
95% sure it's not configured.
yea its not configurated
!ide
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
ok ill do that
try to completely avoid searching objects by name
oh because what im trying to do is getting a array from the npc
that array contains the dialogue
npc holds dialogue?
should probably make a seperate component for that
any script you put on gameobject is component
on so are you saying that i should create a gameobject with only dialogue script?
no just a seperate component, but don't worry about that now. What name did you assign. in the inspector .?
the name i assigned for the script i showed?
its called npc
thats it
i could show the whole script
were you trying to search the component or the gameobject was also called "npc"
The gameobject
screenshot the heirarchy with this script selected also
Ok
btw in meantime configure your ide
Its because im trying to get the name of the npc which i was going to interact
it would've technically worked but your name in the inspector is BLANK. Its searching for an object with empty string name
but still bad practice to search by name. Search by component
in this case link it through the inspector if they're in the same scene
how about this
public class DialogSteps
{
public int steps;
public UnityAction<string, Dictionary<string, string>> Proceed;
public Dictionary<string, string> data = new();
}
public interface IDialogStepMethods
{
public void Init();
public void InitUi();
public void OnProceed();
public void GetInputErrors(string ignoreQuery = null);
public void IsInputValid();
}
-> usage
class myScript : IDialogStepMethods{
private DialogSteps dialogStepSystem;
Init(){.....}
InitUi(){.....}
....
}```
myScript implements the interface now yes.
you would need to do new myScript() to create one
Oh but i thought you needed the game object to search for component
even if its gameobject script that will inherit monobehaviour in runtime?
Or maybe im confusing something else
Then you create it by attaching it to a GameObject
Note it's not a "gameobject script", it's a Component.
ohhhhhhh
there is a static function that searches all object in heirarchy for objects with that component, but its a bit safer than using a string (prone to many mistakes)
So i create another script for this?
You would need : MonoBehaviour for that as well
Ok i get it now
well its good practice to split up responsibilities, but as a bigger its okay if you want to put it in one script
you don't want your scripts to cram different responsibilities in a monolith, gets harder to debug later
Oh
👍
Ok i understand why its a bad practice now. But what ars the other options?
ive got issues with this line of code when it comes to trying to rotate a rigidbody object toward my mouse position on the screen
because i enabled the cinemachine plugin and used a cinemachine camera for it, it wont rotate toward the exact location of the mouse position, and instead just lazily wobbles around in a seemingly random direction
im not sure is there are other parameters i need to set in the cinemachine camera for this to work properly
there is also a seperate issue with the game playtest locking the mouse and causing this line of code to become unable to perform, so if anyone knows how to make sure i can playtest without locking the mouse, i would also appreciate that
Cinemachine camera probably fighting with the repositioning of your cursor because you're using screen to world. As the camera moves, so does the pointer position so I expect that be a problem. I think as a bandaid you can just check when the cursor is moved instead of constantly calling this in fixed update
does anyone know like why my turret targets random enemies and not target the enemy closest to the base?
still looking into this and something ive been looking at is the near clip plane i have set for my camera
i have it bound to roughly where the edges of the screen are, but i need to figure out a way to translate this into that rotate function i have set
Your turret does whatever your code tells it to do
how would i make it where it targets the enemy closest to base
Have it pick the enemy with the closest distance to the base amongst all its valid targets
thanks!
Without seeing the existing code it's hard to be more specific than that
the function is working when playing unfocused - but every few seconds into playing it, the function just breaks and stops working
no reason to be using nearclip plane, you should be using Orthographic
0 out the Z
i uhh
have my camera on perspective mode rn because i was thinking about using it for a 2.5d effect
I'm not entirely sure what you're aiming for here. I'm assuming that the camera pans out towards the cursor, but you're saying it should rotate which I'm not sure what that's about.
if you use perspective then you would use a plane to raycast on
the camera shouldnt be moving or rotating, the gun's the object that im wanting to rotate when the mouse moves
So the camera should stay perfectly still, but as you move your gun the camera moves?
no not at all
the camera is still all the time
the gun moves with the mouse
In that case you may be focusing a gameobject with the cinemachine camera which is rotating but instead you want to be focusing on something that doesnt
Ok, so then it's not a cinemachine issue?
i have no idea what's causing it anymore right now, i got it to work like 5 minutes ago for a brief moment and now it's broken
I'd retrace your steps and disable the plugin/go back to how you had it and see if it persists
ok so when the camera is moving it's what's causing the function to break
because when i move the character, the camera moves with it, and the mouse position should just be the same and track with the camera
I'd probably need to see a video of it and maybe the hierarchy
Oh you did post the hiearchy and yeah that's fine
!ban 1297220734875340840 spamming
star_firevr was banned.
I have a beginner question for you guys. I'm following a tutorial series and anytime they want to access a gameobject in a script they create a variable for it even if the script is attached to the object we are using.
i.e
Rigidbody rb;
rb =GetComponent<Rigidbody>();
Is there any reason to do it that way compared to just using:
this.GetComponent<Rigidbody>()
when the script your using is only going to be attached to the object you are modifying.
imagine if everytime you left the house in the morning you couldn't find your keys
vs. having them on a little plate or something all the time
doing the former avoids having to go find them everytime, even if there's only a couple places it could reasonably be
As batby implied, we're using a little bit of memory here (the variable) to avoid calling the function a bunch of times which is both ugly in code and has a performance impact.
Oh i see. It sores the rb in memory instead of having to call for it every time basically.
makes sense
Nitpicking but the rb is stored in memory regardless, what we are storing (called “caching” in this context) is the location of it
Yeah we're storing a reference to the RB in memory.
Kinda like someone giving you the address to their house
how will u guys cut off the repeated code from here?
case 1:
if (!dialogStepSystem.Data.ContainsKey(DialogSteps.DataKeys.SecurityQuestion1) || !dialogStepSystem.Data.ContainsKey(DialogSteps.DataKeys.SecurityAnswer1))
{
return null;
}
dataForValidate.Add($"security_question{step}", dialogStepSystem.Data[DialogSteps.DataKeys.SecurityQuestion1]);
dataForValidate.Add($"security_answer{step}", dialogStepSystem.Data[DialogSteps.DataKeys.SecurityAnswer1]);
return CustomFunction.SecurityQuestionAnswerValidate(questionInputField.text, answerInputField.text, dataForValidate);
case 2:
if (!dialogStepSystem.Data.ContainsKey(DialogSteps.DataKeys.SecurityQuestion2) || !dialogStepSystem.Data.ContainsKey(DialogSteps.DataKeys.SecurityAnswer2))
{
return null;
}
dataForValidate.Add($"security_question{step}", dialogStepSystem.Data[DialogSteps.DataKeys.SecurityQuestion2]);
dataForValidate.Add($"security_answer{step}", dialogStepSystem.Data[DialogSteps.DataKeys.SecurityAnswer2]);
return CustomFunction.SecurityQuestionAnswerValidate(questionInputField.text, answerInputField.text, dataForValidate);
case 3:
> same as step 1 and step 2```
use arrays
let me try
var data = dialogStepSystem.Data;
var keys = DialogSteps.DataKeys;
var question = keys.SecurityQuestions[step];
var answer = keys.SecurityAnswers[step];
if (!data.ContainsKey(question} || !data.ContainsKey(answer) return null;
dataForValidate.Add($"security_question{step}", data[question]);
dataForValidate.Add($"security_answer{step}", data[answer]);```
that's just a first pass^ there's more you can do no doubt
this dataForValidate dictionary and the use of the strings here also seems suspect.
Basically any time you find yourself numbering your variables like that (e.g. SecurityQuestion1) you should be using an array or a list instead.
public enum DataKeys
{
Username,
OldPassword,
Password,
SecurityQuestion1,
SecurityQuestion2,
SecurityQuestion3,
SecurityAnswer1,
SecurityAnswer2,
SecurityAnswer3,
Phone,
CountryCode,
NickName
}```
I did not expect that to be an enum
regardless, put all the enum values you want to process in an array and iterate over it
instead of using them individually this way
we have multiple steps dialogs, each steps will need u to fill in 1-3 fields, or elements, cause its annoying to let users fill in only one type of data and spam the Next button hard right
i was thinking of containing the data with Dictionary<int,string>, but i cant because of this
so i turned to enum
and then enum has this issue
and yeah i do need to record whats user entered because i need to send it to server for processing
but yeah i do get the message, thx
Want to use specific collision for the character
Like accurate not capsule
Is there any way to get a serializedfield in the inspector to update after adjusting the number in the script?
I've tried playing/stopping etc but the number in the inspector does not update to the new number that was set inside the script.
You mean the field initializer?
public int x = 5;``` ^ the 5 here?
You would have to Reset the script
(... menu -> Reset)
that will reset everything on it btw.
Ok yea Rclick-> reset fixes it. I wish it would just update when it reloads the script though....
that would be awful
it would break pretty much every game immediately
If you intend for rocketSpeed to never be different on different objects, there's no reason to serialize it in the first place
Imagine you set up 500 different rockets with different speeds, and then you changed that one number in the code and you lost all that work
it's mostly just for testing different speeds, But i can forsee how it could cause issues after actually thinking about it.
that's what the inspector is for
I wasn't thinking about other usecases outside of my own haha.
hey
Im trying to make a small code input sort of puzzle
and I cant seem to get this thing to do the click once
instead of going the limit
sorry are you saying your problem is its clicking too many times when you only click once with your mouse?
okay, I'm having two main issues here:
1st: when pressing on spacebar (which is the main key for the spaceship movement) and crashing into an object, the componentmainEngineAudio which is found in Movement file keeps working even though I'm disabling it in CollisionHandler file
2nd: in order to get the audio component OnCollisionAudio working in game, so right before crashing into an object (whether the ground or an obstacle) i need to lift my hand off the spacedbar key to get it working (meaning if i crash into an object while pressing on the spacebar the collision audio won't work (watch the video the understand more)
Here are my scripts as well:
``Movement` Script:
using UnityEngine.InputSystem;
public class Movement : MonoBehaviour
{
[SerializeField] InputAction thrust;
[SerializeField] InputAction rotation;
[SerializeField] float thrustForce = 10f;
[SerializeField] float rotationSpeed = 10f;
[SerializeField] AudioClip mainEngineAudio;
AudioSource audioSource;
Rigidbody rbody;
void Start()
{
rbody = GetComponent<Rigidbody>();
audioSource = GetComponent<AudioSource>();
}
void OnEnable()
{
thrust.Enable();
rotation.Enable();
}
void FixedUpdate()
{
ProcessThrust();
ProcessRotation();
Audioing();
}
void ProcessThrust()
{
if (thrust.IsPressed())
{
rbody.AddRelativeForce(Vector3.up * thrustForce * Time.fixedDeltaTime);
//Debug.Log("Thrust is pressed");
}
}
void ProcessRotation()
{
float rotationInput = rotation.ReadValue<float>();
if (rotationInput > 0)
{
ApplyRotation((rotationSpeed * -1));
}
else if (rotationInput < 0)
{
ApplyRotation(rotationSpeed);
}
//Debug.Log($"Rotation is pressed: {rotationInput}");
}
void ApplyRotation(float rotationStrength)
{
rbody.freezeRotation = true;
transform.Rotate(Vector3.forward * rotationStrength * Time.fixedDeltaTime);
rbody.freezeRotation = false;
}
void Audioing()
{
if (thrust.IsPressed())
{
if (!audioSource.isPlaying)
{
audioSource.PlayOneShot(mainEngineAudio);
}
}
else
{
audioSource.Stop();
}
}
}```
and CollisionHandler Script:
using UnityEngine.SceneManagement;
public class CollisionHandler : MonoBehaviour
{
[SerializeField] float delay;
[SerializeField] AudioClip OnCollisionAudio;
[SerializeField] AudioClip sucess;
AudioSource audioSource;
void Start()
{
audioSource = GetComponent<AudioSource>();
}
void OnCollisionEnter(Collision other)
{
switch (other.gameObject.tag)
{
case "Friendly":
Debug.Log("You've hit Friendly");
break;
case "Finish":
Debug.Log("You've hit Finish");
audioSource.PlayOneShot(sucess);
Invoke("DisableMovement", 2f);
Invoke("NextLevel", 3f);
break;
case "Fuel":
Debug.Log("You've hit Fuel");
break;
default:
Debug.Log("You Crashed!!!");
DisableMovement();
PlayCollisionAudio();
Invoke("ReloadLevel", delay);
break;
}
}
void ReloadLevel()
{
int levelIndex = SceneManager.GetActiveScene().buildIndex;
SceneManager.LoadScene(levelIndex);
}
void NextLevel()
{
int levelIndex = SceneManager.GetActiveScene().buildIndex;
levelIndex++;
if (levelIndex == SceneManager.sceneCountInBuildSettings)
{
levelIndex = 1;
}
SceneManager.LoadScene(levelIndex);
}
void DisableMovement()
{
GetComponent<Movement>().enabled = false;
}
void PlayCollisionAudio()
{
if (!audioSource.isPlaying)
{
audioSource.PlayOneShot(OnCollisionAudio);
}
}
}
Any help guys?
- Disabling the movement script isn't going to make the sound stop playing. there's no reason it would.
- Because you are doing an
if (!audioSource.isPlaying)check before playing the collision sound. So if it's already making the engine souind it's not going to make the crash sound
thanks for your help i really appreciate that
however there are things i don't undersand,
1st isn't the audio component mainEngineAudio a part of movement script? in other words wouldn't simply disabling the script also disable all the methods / components that are within?
2nd what i understood, the collision sound wouldn't work because there's an audiosource that is already playing mainEngineAudio ig, what's your suggestion to fix that? make another audio source component?
I'm still a beginner in unity btw
1st isn't the audio component mainEngineAudio a part of movement script? in other words wouldn't simply disabling the script also disable all the methods / components that are within?
No. The movement script simply references the AudioSource component and calls some functions on it. THe AudioSource is still a completely independent component.
2nd what i understood, the collision sound wouldn't work because there's an audiosource that is already playing mainEngineAudio ig, what's your suggestion to fix that? make another audio source component?
Just get rid of theif (!audioSource.isPlaying)check around playing the collision sound. I don't understand why you have it there.
One thing that you need to understand asap is that scripts are components as well. Components can't be attached to components, only to gameObjects.
If you were to deactivate the GameObject that would've worked.
i see
this will come in handy ngl
much appreciate your help guys
code it
how to swim?, i have water(plane) there is nothing under it, i want to keep the head out of the water
- detect if the character is in water
- apply "in water" logic/physics
I want to change this code to use NavMeshLinkData instead of OffMeshLinkData, but I'm not sure how to modify it.....
help
I am using a translator so my reply may be strange or late...
just spent Way too long at a loss for why my runtime sculpting system was only detecting Back facing vertices, instead of only Front, which i wanted.
Vector3 viewDir = (worldVertex - camPos).normalized;
should have been
Vector3 viewDir = (camPos - worldVertex).normalized;

Everything in programming is difficult when you know next to nothing about programming :/
Relatable lol
what do you want to do with it ?
NavMeshLinkData is a struct you can create
I want to convert the code that uses OffMeshLinkData to use NavMeshLinkData instead.
navAgent doesn't have NavmeshLinkData
ah
OffMesh = part of the link thats not on the mesh
NavMeshLinkData used to manipulate runtime link https://docs.unity3d.com/6000.0/Documentation/ScriptReference/AI.NavMesh.AddLink.html
I see. Then I guess I should change it completely.
I have a lot of questions, but I can't ask many because I don't speak English.
Thank you for your answer.
// state
private enum state {
AIR,
WALK,
IDLE,
JUMP,
SLIDE,
CROUCH,
}
private state player_state;
public void state_manager() {
if (player_rb.linearVelocity.magnitude <= 0) {
player_state = state.IDLE;
}
else {
player_state = state.WALK;
}
if (Input.GetKeyDown(crouch_bind)) {
if (player_state == state.IDLE) {
player_state = state.CROUCH;
}
if (player_state == state.WALK) {
player_state = state.SLIDE;
}
}
if (Input.GetKeyDown(jump_bind)) {
if (player_state == state.AIR) {
return;
}
player_state = state.JUMP;
}
if (player_state == state.AIR) {
if (!is_grounded()) {
return;
}
player_state = state.WALK;
}
}
public void slide() {
// early exit
if (player_state != state.SLIDE) {
return;
}
player_rb.AddForce(transform.forward * 10);
// idk how to check if slide ended
player_state = state.WALK;
}
public void jump() {
// early exit
if (player_state != state.JUMP) {
return;
}
player_rb.AddForce(Vector2.up * jump_force);
player_state = state.AIR;
}```Heyo, I was wondering if anyone can help me. I am trying to write movement and everyone uses states. I tried some implementation, but it looks wrong the code is hard to maintain cause i have to set and reset states from different functions which becomes incredibly confusing. I was wondering if someone can explain how I could implement something like this. Maybe even provide a code sample. Cause if i want to add even more states it will lead to even more if clauses and confusion.
public interface IDialogStepMethods{
public DialogSteps DialogStepSystem { get; }
}
class A : IDialogStepMethods{
public DialogSteps DialogStepSystem { get; private set; } = new();
}
this is a valid implementation right?
does it error? if not, then yes it's valid
nice
(but yes that's most likely valid)
finally optimized
Going to sleep but this is usually what I start with:
public class Player : MonoBehaviour
{
public enum State { Idle, Walking }
public State CurrentState { get; private set; } = State.Idle;
private void Update()
{
switch (CurrentState)
{
case State.Idle:
// Idle logic
break;
case State.Walking:
// Walking logic
break;
}
}
public void ChangeState(State newState)
{
if (CurrentState == newState) return;
OnBeforeChangeState();
CurrentState = newState;
OnAfterChangeState();
}
private void OnBeforeChangeState()
{
switch (CurrentState)
{
case State.Idle:
break;
case State.Walking:
break;
}
}
private void OnAfterChangeState()
{
switch (CurrentState)
{
case State.Idle:
break;
case State.Walking:
break;
}
}
}```
(https://paste.ofcode.org/V8Tiajh9amwRXRnQZXNz9i)
So rn im trying to implement a jump mechanic where if i jump while moving toward a wall, I slide against the wall since i want to have momentum. This feature was working but I then implemented a feature where if Im jumping while moving forward against a lower object like a cube, I dont gain velocity until my character is above it and able to move forward, since before I was still gaining velocity while not moving causing my character to overshoot the jump.
How can i fix/implement this?
Can someone help me figure this out. I am trying to record a animation with some VFX and shader graph included. I created a cinemachine and started receving hundreds of those error per second and I am not even playing the game
apparently restarting Unity helped
I am using pooling for my bullets
its that way of implementation of Coroutine is good ?
using UnityEngine;
using System.Collections;
public class BulletData : MonoBehaviour
{
public float dmg;
public BulletPoolManager bulletPoolManager;
private float timeAlive; //place holder if i will add timeDepended DMG
private float lifetime;
private Coroutine destroyCoroutine;
private void OnEnable()
{
lifetime = 5;
timeAlive = 0f;
destroyCoroutine = StartCoroutine(DestroyAfterTime(lifetime));
}
private void OnDisable()
{
if (destroyCoroutine != null)
{
StopCoroutine(destroyCoroutine);
destroyCoroutine = null;
}
}
private IEnumerator DestroyAfterTime(float time)
{
yield return new WaitForSeconds(time);
bulletPoolManager.ReleaseBullet(gameObject);
}
how do i make weapon recoil
Lol
Good thing AI out here revealing all these tutorials as scams with you at the helm!
hi
i have a problem with my player's ground sliding mechanic
i added some logs to see if the slide is working and the thing that i saw was this: the slide IS working BUT when I press the button the player won't slide, it will stay where it was(but still it can go left or right or jump)
i noticed that the player's movement script is overriding the rb.linearVelocity but i couldn't fix it. i tried to disable the player's movement script in the player's slide script but that didn't work
i also asked this from AI but no it couldn't fix it
anyone can help me?
where can i share the code?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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.
okay
Hey guys, Is it real that If I want to pause the game I have only 2 ways:
- Time.timeScale = 0f
- Create a flag and check everywhere that my game is paused ?
Well, the first one isn't really a pause, it'll only affect things that use deltaTime
which, is a lot of things that move, to be fair
do you have any suggestions how to make it properly?
Basically that second one. Make some sort of Singleton that determines whether the game is paused or not, and check that value in your scripts
Insane
okay so this is the player's movement code-> https://paste.myst.rs/p4jjz1uo
and this is the player's slide code -> https://paste.myst.rs/buouexbt
a powerful website for storing and sharing text and code snippets. completely free and open source.
a powerful website for storing and sharing text and code snippets. completely free and open source.
this is what i need help with
canomeone help me please?
can someone*
The major issue here is that you have a script for your player's movement which handles normal movement, jumping, wall sliding and wall jumping, then you've decided to, for some reason I can only assume is that you've found this slide code online, seperate another movement state into its own script.
Of course if you're going to explicitly set the linearVelocity in both scripts, it's going to take one over the other.
using UnityEngine;
using UnityEngine.EventSystems;
[RequireComponent(typeof(AudioSource))]
public class SoundOnClick : MonoBehaviour, IPointerClickHandler, IBeginDragHandler
{
public AudioClip clickSound;
private AudioSource audioSource;
[SerializeField] private ClickToBig IsBig; // Reference to ClickToBig script to check IsBig status
private void Awake()
{
audioSource = GetComponent<AudioSource>();
if (clickSound == null)
{
Debug.LogWarning("Click sound not assigned on " + gameObject.name);
}
}
public void OnPointerClick(PointerEventData eventData)
{
// If the object is big, do nothing on click
if (IsBig != null && IsBig.IsBig)
{
return;
}
// If not big, play the click sound
PlayClickSound();
}
public void OnBeginDrag(PointerEventData eventData)
{
PlayClickSound();
}
private void PlayClickSound()
{
if (clickSound != null)
{
audioSource.PlayOneShot(clickSound);
}
}
}
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class ClickToBig : MonoBehaviour, IPointerClickHandler
{
[SerializeField] private Vector3 _bigScale = new Vector3(20f, 20f, 20f);
[SerializeField] private Vector3 _smallScale = new Vector3(5f, 5f, 5f);
[SerializeField] private bool _isBig = false;
private RectTransform rectTransform;
[SerializeField] private RectTransform objectToResize;
[SerializeField] private Button closeButton;
private void Start()
{
if (closeButton != null)
{
closeButton.onClick.AddListener(ShrinkObject);
}
}
private void Update()
{
rectTransform = GetComponent<RectTransform>();
rectTransform.SetAsLastSibling();
}
public bool IsBig
{
get => _isBig;
set
{
_isBig = value;
if (_isBig)
{
if (objectToResize != null)
{
objectToResize.localScale = _bigScale;
}
}
else
{
if (objectToResize != null)
{
objectToResize.localScale = _smallScale;
}
}
}
}
public void OnPointerClick(PointerEventData eventData)
{
if (_isBig)
{
return;
}
IsBig = !_isBig;
}
private void ShrinkObject()
{
if (_isBig)
{
IsBig = false;
}
}
private void OnValidate()
{
IsBig = _isBig;
}
private void OnDestroy()
{
if (closeButton != null)
{
closeButton.onClick.RemoveListener(ShrinkObject);
}
}
}
I have an object that starts small and when clicked on, it plays a sound and grows big. I tried adjusting the script to disable the OnPointerClick while the object is big so that it doesn't make a sound. While that is the case when big, It doesn't play any sound from the beginning when it is small.
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 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
in response to your question mark ping. its literally the 2nd line of the bot message
The scripts are inline though
thats great. now read the part about 📃 Large Code Blocks
also, add debugs. this isnt some complex logic to follow, you should print out the values or use a debugger and see exactly what values are so you know why you have a problem
Thanks for the help
This is how much I have to zoom out to view them at the same time. How does that not qualify as "Large code blocks"
A tool for sharing your source code with the world!
Okay, and the issue is that the sound isn't playing, right?
Where do you assign IsBig in SoundOnClick
With the adjustment on OnPointerClick in the sound script. Originally it was just PlayClickSound within OnPointerClick
Serialized field and in Unity, "Is Big" has the object dragged into field
So, your if condition is evaluating to true. Try logging IsBig.IsBig before the if
That's not how you log something
And why did you take it out of your if
yes I just have this
public void OnPointerClick(PointerEventData eventData)
{
if (IsBig != null)
{
Debug.Log("IsBig.IsBig: " + IsBig.IsBig);
}
if (IsBig != null && IsBig.IsBig)
{
return;
}
PlayClickSound();
}
Okay, so it's True, which means it hits return and doesn't play the sound
Also, do you ever expect a situation to come up during normal play where IsBig is null?
Will you ever intentionally be leaving out IsBig?
How would I perform a raycast in a set range? I've tried spherecast but doesn't seem to work as expected, I just want to raycast for objects in range
In a set radius 360 degrees around the character, independant of the camera or angle
CheckSphere
SphereCast is throwing a sphere and seeing what it hits. CheckSphere is checking what's inside a stationary sphere
When the object is large, a dialogue box appears as apart of a separate script and manager. When the Close button is clicked, the object returns small (which the only way to make it small during gameplay).
Okay I'll try that thank you
Oh wow, the checksphere is also alot easier to implement than spherecast
Your sound script doesn't care about any of that. It checks if IsBig is set, and if it is, if IsBig's IsBig is true. Which it is, so it exits early and doesn't play the sound
Right, like if I change the second if to "if (IsBig == null && IsBig.IsBig)" then I get the sound back just like pre-modifying.
Yeah, sphere cast is basically just a thicc raycast, so you need to provide a direction and distance. It won't detect anything that starts in the sphere, so it can't be used to check around the starting area.
im having issues right now tho
That if statement doesn't make sense. If IsBig is null, how are you supposed to check IsBig.IsBig
well that doesnt make sense.. how can IsBig null and yet ur next condition is using it IsBig.IsBig
NullReferenceException: Object reference not set to an instance of an object
PlayerInteraction.Update () (at Assets/Scripts/PlayerInteraction.cs:24)
void Update()
{
Ray ray = new Ray(transform.position, transform.forward);
bool successfulHit = false;
Debug.DrawRay(ray.origin, ray.direction * (_interactionRadius * 2), Color.green);
if (Physics.CheckSphere(transform.position, _interactionRadius))
{
Interactable interactable = hit.collider.GetComponent<Interactable>();
if (interactable != null)
{
HandleInteraction(interactable);
_interactionText.text = interactable.GetDescription();
successfulHit = true;
}
}
if (!successfulHit) _interactionText.text = "";
}```
if (Physics.CheckSphere(transform.position, _interactionRadius))
this line
line 24 references something not assigned or null
Again, will there ever be a situation in which IsBig is intentionally left null?
Can you share the full !code to a bin site so we can see line numbers
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
This was half the script if you dont mind having it here
CheckSphere doesnt have a hit
its a boolean
no clue why it doesnt
oh
then how do i work around this
OverlapSphere has an array of colliders
Collider[] colliders = Physics.OverlapSphere(transform.position, _interactionRadius);
foreach (Collider col in colliders) {
Yeah, Check sphere checks if anything is in range. Overlap tells you what is in range
theres an nonallocated version
if u know like a nice limit u wanna use so ur not resizing arrays all the time
Not necessary at the moment I think.
Oh i see, that's so easily misunderstood
like if ur only anting to grab the first of something
i dont see why ud need it
yea u right digi
just figured id mention it
It's an optimization, but make it work first, then make it fast
I dont carea bout optimizations at the moment I just wanna get comfortable with the different functions
oh, then go hamm 🐖
I have a good structure of knowledge when it comes to scripting in gereral it's just getting used to all the different functions
yea, you'll have that for a while
Like checksphere. spherecast or overlapsphere, so similar yet very different
autocorrect helps
I suppose
Yeah, for the physics queries there's a bunch of em with their own niches
That's useful
Yeah I see
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Physics.html
Look under "Static Functions" for most of them (and a few non-query things that might still be good to know about)
also when u hit that optimization part.. use a TryGet as opposed to a GetComponent and null check
Start of the scene and when the dialogue box gets closed
it kinda does both at the same time
Okay, so, during normal play, there is a time in which someone could click on this object, and IsBig is null, by design?
spherecast u can think of like a thick raycast
Yeah, that's what I thought of aswell when I tried it
This is more like it, let's give it a try 🙂
guys, why does unity load my scene which isnt enabled in build settings
yessir.. looks good at first glance
Is GetComponent reliable here? Cause if it doesnt find the component, it'll just be null, correct?
At runtime or in editor? The editor can open any scenes you ask it to. In a build, it'll only load ones in the build settings
its fine for now.. TryGets are better tho..
No, but that's what your null check is for
That'll cover the situation in which the thing you find doesn't have that component
in runtime, thats very weird
Yeah I nullchecked, But other languages often error because it doesnt find it, so I'm not used to this
Oh, it's beautiful
Works as expected 🙂
In this case, it just returns null:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/GameObject.GetComponent.html
Returns:
TA reference to a component of the specified type, returned as an object of typeT. If no component is found, returnsnull.
Thank you
Unless you're loading the scene from a bundle or addressable, it won't be included in the build and can't be loaded
wait ill show
That cannot happen and shouldn't
So, if IsBig is always set, and is not ever intended to be null, then you shouldn't do those null checks. Remove the IsBig != null. If it's ever null, that's a problem and you want to know about it.
With the extra null checks, you could have an IsBig not set and literally never know about it and have your buttons misbehaving with no indication
if(mycodeisbroken){KeepItASecret();}
been ther.. done that..
so, after many systems i realize that depending on how hard i try to structure before hand my scripts typically end up all relying on atleast 2 others.. none minimum, and 3 maximum.. i still find myself having to draw out little flow charts to keep up sometimes.. is this too much still?
nothing extravagant mind u.. just isolated things.. like (do this, change ui to this, remember that)
Don't get hung up on the number of references, think about the direction of references. Try to keep a sort of "Data flow". You could have a dozen scripts that all reference one central script, but make sure that central script doesn't reference any of the ones lower down
Spaghetti Code is not caused by having too many references, but by having too many directions
most all of em have that in common as well
they all notify some bigger entity
but not referencing any lower downs make sense
This is where properties and events come in handy. If a lower-down script changes a variable in a higher-up script, that script can then invoke an event and anything lower-down can subscribe to it and know when it's changed
yessir! 💪 im warming up to events
The higher-up script doesn't have any idea about the kinds of things subscribed to it
properties not just yet
They're just functions that are called when you access/change a variable
If, instead of a property, you had public ___ GetSomeVariable() and public void SetSomeVariable(___ value) it'd be the same thing
i'll get there.. but for now it just complicates things in my head. i'll use them sparingly tho
it just feels like i end up with duplicates to everything when i try it lol..
do you know of any particular system or game feature that i could try out to practice using properties?
anything that would make a good use for them
Honestly I can't really think of a game feature that doesn't benefit from properties
darn.. lol
i wanted something that kinda forced my hand.. guess ill have to discipline myself
It runs code when a variable changes - that's fantastically useful
Have an object's Health variable handle all the checking for death and overhealing all in one
So you just do Health -= 10 and boom, donezo
b/c i can already find lots of stuff like that ^ yea exactly
The property does the rest