#💻┃code-beginner
1 messages · Page 551 of 1
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
they are more specific / tailored to learning c# and Unity + c# api
I don't like courses. 80% of this would be a time waste for me. I'm doing purely a code approach with algorithms.
I'm almost completely not dealing with scene objects and it's properties (bare minimum configuration, I'm not creating a game ;p)
Yep this works really well
alright well best of luck, if you don't like courses its never too late to actually study the docs/manual.
whatever you doing, It might be quicker at first but you will spend more time fixing mistakes undoing bad patterns
ooh ok
Which part are you trying to figure out now?
just with how to do the sound playing when the object takes damage and gets destroyed
i think i figured out something though?
would this be a ok solution? AudioSource.PlayClipAtPoint(damageSFX, transform.position);
and the variable is public AudioClip damageSFX;
which is set in the inspector for each object
This works for now, you'll only need to change this code if you want to do volume sliders
I'm just gonna say in advance that this PlayClipAtPoint spawns a GameObject with an audio source. It returns that GameObject too
is there a way to change the volume/pitch of a playclipatpoint?
its very limited
Yep you can, since it returns the gameobject you can get the audio source component and change the volume from there
Oop nvm it doesn't return the gameobject
ooh
You should probably add an audio source to your object
creates a temporary audiosource
also if you do it often is pretty garbagey
much better you make a singleton
other people make an object pool of audio sources and a manager that lets you play the audio anytime
even lets you select the mixer(for when you want to adjust the volume slider)
^ or a pool if you need localized 3d sounds instead of singleton sound manager script
I feel gaslit, I always thought PlayClipAtPoint returned the gameobject it created
PlayClipAtPoint is a quick dirty solution, as soon as sound is done it destroys
hence the potential to make so much garbage
ya i dont need localized 3d sounds just a normal sound that gets played
SoundManager.Instance.PlaySound(yourSound) or enum whatever
you'll think about the problem when you encounter it in future 😃 aka when you have hundreds of sounds playing at the same time
pooling your audio objects will save you a lot of compute
pooling is only needed if you need to spawn them as local 3D sounds emitting from their position
otherwise a Singleton suffice
to be fair you can make them 3d and teleport them to the location
or 2d and let it play
but if you got multiple sounds at same time which one does your soundmanager singleton prioritize playing local 3d
What are you creating then if i may ask?
I tried singleton for 3D sounds, had to use Instantiated pooled sound objects
every time you PlayGlobal it finds the first inactive GameObject in the pool and sets the values from there like if it's 2d or 3d
idk what you mean "Global"
I mean 3D sound . Singleton is kinda useless there
easier to spawn a SoundObject (sure use pooling)
You can PlayLocal(Vector3 position, enum sound) which teleports the object there
How would i setup singletons for my sounds that i want to be played when my different objects take damage or get destroyed?
IMO. I would register whatever makes sounds to the SoundManager then listen to specific events for specific sounds
I only need one singleton. Not singletons
huge terrain generation based on a heightmap or possibly a binary file because images could be heavy very fast when increasing the size
the terrain will be split into chunks and they will have LoD changed based on a distance to the camera
I know there is a plugin for it but I will have to have 100% code control over it to customize it further
It has void return type tho 🤔
Neat. I have made similiar stuff
Unity is great for stuff like this IMO
One thing is sure. Godot is not 😄
What is the use case? Do you export the terrain and use it somewhere else?
If you want to make it easier on yourself and not deal with events yet, and sound is global, put the AudioClip only on the gameobject then pass that to the sound manager when you want to play
eg
[SerializeField] AudioClip hitSoundFx;
void Hit(){
SoundManager.Instance.Play(hitSoundFx)```
@junior ivy Also have you looked at compute shaders for the terrain generation?
Or shaders in general
Or do you do it on the CPU
yeah, that might be used as a level generator and reader
I'm having fun mostly, nothing specific
so much wrong going on here lol
first of all thats not how you write an IF statement, we don't use {} for the condition
so what do you use?
you use parenthesis ()
i always thought it was {}
currently I think the cpu is enough because it's not* the infinite terrain but I'm aware of this, I started game dev wtih WebGPU and its WGSL shading language
ohhhh
is to Open a code block
{
}
check out the pathways on !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
me?
esp junior programming
You
your IDE is already configured, you're 60% ahead of people who come here for help
my ide is visual studio right?
(
if{ Input.GetKeyDown(KeyCode.Escape); }
{
}
)
no lol
yes i noticed those
what
don't just guess. look at the basic if statment
how
okok im looking
also your comment in the code is misleading void is NOT a method
void is a Return type for the method
methods can also return objects, like int bool another script. etc.
I don't think game dev is the best way to learn programming 💀
You can but its more to deal with it. Easier to do the basic c# courses then slowly dive into unity specific
For me it was the only motivation to learn programming
Probably not the easiest route though, depends on the person i guess
i got it
learning on Console/Terminal might not be as stimulating
which comment is that?
the one on the bottom ?
the only comment that says "void is a function"
//void is a function
I started programming with scraping google SERP with IP changer and hacking, better than a moving things in the screen tho :>D
well yeah thats a different fulfillment ofc. the end result is the motivator
thats correct
I started with Klik & Play which was a game making program that used a sort of "event sheet"
It helped me understand the logic without having to learn code
Similiar to gamemaker or multimedia fusion
Same :D
the examples were so funky lol
Oh god I vaguely remember there was some clown stuff or something horrifying with weird ass sounds and graphics
wait im confused is that hitSoundFx variable with the serializefield supposed to be on my ResourceNode script? and the SoundManager.Instance.Play(hitSoundFx) is supposed to be under my DamageNode() Method in my resource node script also?
And then i make an empty game object called SoundManager and have the 2 audio sources on that?
the sound itself should be on whatever you want that object to make specific sound, you dont need to put it there though esp if you have generic sounds not specific to certain objects
yeah Damage method would call the SoundManager to play the sounds, or put the sound player on resource itself . Up to you
for now im just reutilizing my footstep and dash sound effects but i eventually want unique rock cracking sounds or wood cracking sounds specific to each object
that comes down to how you eventually identify type of sounds based on your item
For stuff like footsteps (or hit sounds), I'd have a component on each object that stores its "material type"
It could be an enum or a scriptableobject reference
And you'd use that to get the correct sound
I didnt really follow your convo tho so idk what the issue is
yeah pretty good approach too. I think they want to play a sound when they drop a resource/break it
The same material type can be used to decide if hitting an object should spawn dust, sparks etc.
I use SO's
I have a question about my input action. for some reason it's not working. logging everything doesn't give me any logs. nothing is firing. it's on the select button on my controller. i have my start button mapped and working, and i did the exact same set up and it's not working for select.
how can i debug this?
just curious, do you run a switch to identify or is it like stored on SO the sound
I'm still trying to break free from enums because of giant switches
The component on each object has a direct reference to the SO
And the SO has a direct reference to a sound
(FMOD event in this case)
ahh ok audioclip stored on so, makes sense
im ngl i still dont think i understand the SoundManager.Instance.PlaySound(damageSFX); part
how do i get the SoundManager exist in the current context in my ResourceNode script
was just an example but can clarify if you tell me what part you don't
I do still use enums for some things like "bullet hole type" and "debris type"
cause rn its giving me an error when i put those lines in
being a singleton you can access it without a reference
But those enums aren't going to be very large, maybe 10 items each, so it isnt that bad
yeah I saw the codebase for GTA3 AI and had a switch of about 10 for states, i suddently didn't feel so bad for using about the same amount heh
Switch often gets compiled into a dictionary or some other lookup table, as far as i know
As long as the switch is large enough
good to know 10ish is not so bad since that usually my max. but yeah at that point its just easier to probably use a Dictionary
how do i make my sound manager with all the differnt sounds on it a singleton?
You create a singleton
so this would be the correct singleton setup for what im trying to do? https://paste.ofcode.org/bnMec7eGrnhWhkpPLDwt5H
I suggest you read the link again
oh i didnt realize i needed to add the whole other part i thought it was just generally recommended
You don’t need to but it is highly recommended in order to have a better dev experience in the future
the if statement checks if instance already exists its just for precautions
would this be better? https://paste.ofcode.org/bqH3CtVWwSsXQC5mcQLrW8
and is that PlaySound method correctly added?
look ok
I would still add the Dont destroy on load part
I do know why you are avoiding just implementing it like in the link provided
What is there is the standard go-to singleton implementation for Unity
oh whoops i missed that part at the top mb
why does this have an error at the bottom with the AudioSource.PlayOneShot(clip); https://paste.ofcode.org/MDdjmvwmcqtwhUJNALDvpS
how do i get it to work with this scripts calling?
AudioSource is a type. You can't call a non-static method directly on a type. You need a reference to an audiosource and call it onthat
you need a reference to the component AudioSource
oops forgot to add the other part for destroysfx https://paste.ofcode.org/HMRhC6XEuWt2GvU8MRLWvV
im confused isn't that already what im doing with the audio clip that im sending in from the other script with the SoundManager.Instance.PlaySound(damageSFX);
or should i change the AudioSource to a AudioClip type also?
AudioClip and AudioSource are not the same thing
AudioSource is the Radio, AudioClip is the song
why does it show this though when its talking about the implementations?
looks fine to me
audioSource is the variable for the AudioSource component
eg
[SerializeField] AudioSource audioSource
AudioSource is the type
audioSource is the instance of that type
and not just using the AudioClip isn't that defeating the purpose of what im trying to do?
What exactly are you trying to do
Maybe you want to create an AudioSource instance that your sound manager uses to play sounds?
just have sounds that can be changed based on which object type it is in the inspector
so if i have glass i can use a glass hit and glass break sound
Btw you have Destroy(this); in the singleton's Awake
It's better to do Destroy(gameObject) otherwise it just destroys the component and leaves an empty gameobject
ok
i also want to be able to change the pitch and volume of each sound
so i can randomize the pitch when i hit something
Unity's audio API seems pretty weak. Why can't you pass the pitch as parameter to the method 🤦♂️
You need to create an audio source anyway
And if you want different pitch for each sound, each one needs its own audio source
As far as i know
where would i create the audio source on so i dont have to have an audio source component on each breakable object in my world?
just on my SoundManager and then somehow activate that from my script
depending on which one is referenced in the inspector of my ResourceNode script
Ideally your soundmanager would manage a pool of audio sources
ok
But for now, you could just do this when you want to play a sound:
-Instantiate a gameobject (var go = new GameObject())
-Add an audio source to it with AddComponent
-Set the audio source's clip, pitch, etc. values you want.
-Play the audio source
-Use Destroy(audioClip.length) or something similair to destroy the audiosource's gameobject after time
am i still able to do that, while being able to refernce which sound is being played from the inspector? Because i want each object to be able to have different sounds
Yes, you can just expand your current PlaySound method
Pass in the audioclip as a parameter, and optionally pitch and volume floats if you want
Then let the PlaySound method handle the rest
^Which is this
does that go in its own script on my soundmanager empty game object?
As I said, you can do it in the PlaySound method
so i just leave everything the same way i have it right now with the singleton and audioclips referenced on my other script and just add that in the PlaySound() method?
If you need the audio be positional (3D, panned based on position) then you need to set the audio gameobject's position and probably some settings on the audiosource too
I dont know much about your other stuff, but you can probably keep it as it is, yeah.
like this stuff in the inspector can stay as it is with getting a reference to the audio clip
and then passing that audio clip in the play sound method like this?
Yes, stop stressing about that 😄
how do i do the second step of adding an audio source with add component?
You search "unity addcomponent" on google and pick the first result which should be the documentation page for AddComponent
Then you read it and look at the examples to figure out how to use it
Try it!
I deliberately left out the code for that so that you learn to look things up
It's very important in game development
is this correct so far
public void PlaySound(AudioClip clip)
{
var go = new GameObject();
go.AddComponent<AudioSource>();
}
Almost - you want to get the reference to the audiosource you added
oki, honestly that's the part i struggle with the most
like i get what i see when i look it up
AddComponent returns the newly added component, do you understand what that means?
but just cant seem to figure out how to use it in my current context
I would recommend you becouse you are still learning how to code to not use var as a variable so you can learn and know witch variable actually is. Becouse var can be any variable depending on the contex.
The examples on the doc page also show how to get the reference of the added component
uhh not exactly
is this correct
public void PlaySound(AudioClip clip)
{
var go = new GameObject();
AudioSource audioSource = go.AddComponent<AudioSource>();
}
the idea was grabbing the audioclip from the Object itself, the soundmaneger can do the rest
public class SoundManager : MonoBehaviour{
public static SoundManager Instance { get; private set; }
[SerializeField] AudioSource audioSource;
private void Awake(){
if (Instance != null)
{
Destroy(gameObject);
return;
}
DontDestroyOnLoad(gameObject);
Instance = this;
}
public void PlaySound(AudioClip clip, float pitch = 1, float volume = 1){
audioSource.pitch = pitch;
audioSource.volume = volume;
audioSource.clip = clip;
audioSource.Play();
//or audioSource.PlayOneShot(clip)
}
}```
Yes looks good so far
This would be a lot less painful if you took some beginner C# course
You can find links to those in this channel's pins
I know a bit of the basics, i just get confused when trying to apply it to different things
like im pretty sure that the line is just Making an AudioSource Variable naming it audioSource and than setting it to the AudioSource Component that was just added to the new gameobject that was made. hopefully that's correct lol
what is the audioSource variable that i put into the serializeField though?
that's what im mainly confused about
the audiosource thats on the Singleton object
but its a monobehaviour so you can link components in the inspector
you can also use multiple audiosources for different purposes
eg
[SerializeField] AudioSource sfxAudioSource;
[SerializeField] AudioSource musicAudioSource;
etc.
so i just make an empty audioSource component on the SoundManager game object? and that gets filled with the audioclip which is selected by the other script?
there is no set way to do it, its all about trial and error with what works best for you
I wouldnt usually put AudioSorce on SoundManager radher the Audio Listener and on the objects that produce the sound i would put audio source.
yes if you link it correctly yes
I only put audiosource on a separate gaemobject if I need 3D audio
if its a global sound / 2D no reason to use multiple AudioSources all over the place
What is the DontDestroyOnLoad(gameObject); part you added doing?
prevents the gameobject from being destroyed between scenes
They wanted to randomize the pitch for each sound so i think they need multiple sources no?
ok cool
when you call PlaySound you can pass a random.range value to pitch
public void PlaySound(AudioClip clip, float pitch = 1, float volume = 1){
audioSource.pitch = pitch;
audioSource.volume = volume;
audioSource.clip = clip;
audioSource.Play();
//or audioSource.PlayOneShot(clip)
}
//other script
void Method(){
SoundManager.Instance.PlaySound(clip, Random.Range(0.4f, 1f));
}```
Yeah but wouldnt that cancel previous sounds
iirc if you do PlayOneShot it should play okay each one without interrupt
And changing audioSource.pitch doesn't affect the previously playing sound's pitch?
it shouldn't if already played the one shot with those settings no? I did not 100 % test it though lol
my sounds were to short to notice
Idk at all, havent used these in years
op can 
I guess you could start with navarone's example and see how it goes
so its better to use PlayOneShot if i dont want to cut off the last sound with the new sound and have them overlap?
yea
i remove the audioSource.clip = clip; and audioSource.Play(); and replace that with the PlayOneShot right?
ya
ok cool
im ngl i cant really tell either if the pitch of the last sound is getting overridden by the new sounds randomized pitch either lol
i mean it sounds fine the way it is i think lol
the only way you can know for sure is playing a really long sound the first time at specific pitch then play another right after with another pitch
ok
but iirc it should just have whatever setting it was at the moment of invoke
PlayOneShot essentially creates a new AudioSource under the hood
does it? isn't that PlayClipAtPoint
why does it need to create another AudioSource from audioSource ref
i could always test with an ambient track i added ig
I know that PlayClipAtPoint does create a new one, not sure if PlayOneShot does
Maybe it does
yeah if while you play the first time track you try play again with another pitch see if the first one switches
ooh yup it does override the sound lol
would seem odd if it did but it can make sense if its agnostic to the current AudioSource to be able to overlap sounds
It's just insane to me that each clip needs its own audio source
it sounds so funny with the ambient track
oh darn
i played the ambient track
then played the rock hit sound
and it changed the ambient track to the pitch of the rock hit
bummer
so its still in the audiosource while plays the clip
now i'm curious how this AudioSource is able to play multiple sounds at once without interrupt on ... i guess a new audiosource can make sense..but wow that would be resource heavy no?
Yeah thats what i expected
So you do need to create a new audio source if you need a different pitch
yea noticeable if the sound is going too long
you can go with Instantiating them too but imo you should pool them but idk if your exp level can handle pooling rn lol
worry about it later if perfomance is really an issue
is it normal to not see anything in the AudioResource spot? while a sound it playing
i thought i saw which one was selected before but now it doesn't show anything in the audiosource
I think that only happens when you do audioclip.clip = no ?
everything I knew about 1 shot is now shattered lol
xd rip
My bad it just takes up a voice channel which is why we do not use it
ahhh ok makes sense
wows thinking it had some type of shit behind the C++ code
thought it was some type of queue or async
do you think it's better to just have the new sound override the last sound by doing the other method instead of overriding the pitch with the oneShot?
new sound also overrides previous sound?
I think if the sound is short enough you probably wont notice the last sound changed pitch to new pitch but thats wonky and not good for long sounds.
btw you can also just have multiple audiosources and split where you play specific sounds types
Buuut I know think that changing the settings of the source doing the one shots changes all playing one shots
Yeah that was my point
yea that makes sense now. I never noticed cause my sounds were to short
And that is the second reason we do not use it
Haven't used methods like that in a while. I use 3D sounds so I'm stuck with pooled objects
Does unity have any new audio API in the works?
oo ok
Or available
isn't unity audio just abstracted Fmod ?
I remember reading them reworking the audio so that they aren't dependent on FMOD anymore or something
well thx so much for the help guys, i think i got everything the way i want it to be for now, i appreciate all the help a ton!
(Unity uses ancient FMOD under the hood)
Oh yeah there was this https://docs.unity3d.com/Packages/com.unity.audio.dspgraph@0.1/manual/index.html
DSP graph
Seems dead though
It’s confirmed dead afik
Two questions:
1: How do I spawn a prefab on my mouse position? I have it spawning just cant get it to go to my mouse
using UnityEngine;
public class MouseSystem : MonoBehaviour
{
[SerializeField] private LayerMask MouseLayer;
private void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Physics.Raycast(ray, out RaycastHit raycastHit, float.MaxValue, MouseLayer);
transform.position = raycastHit.point;
}
}
2: Is there a way to get and spawn prefabs without them being in the scene?
-
Your code looks like it should work, is there another collider it's hitting maybe? IS it moving at all? Have you printed the value of the raycastHit.point?
-
Can you define what you mean by "in the scene"? Do you mean without them being in the hierarchy? If so, you can do something like
public GameObject myPrefab which will give you a field to drop into, and then later var myNewlySpawnedObject = Instantiate(myPrefab)
does ur raycast actually hit a collider?
if you only want it at the mouse position use ScreenToWorld instead
ah, you probably nailed it on that one. That ray has to have something to hit if you use a ray
btw are you using a prospective or ortho camera ?
mb I didn't elaborate one the 1st question. That is for my mouse pointer, that works, I was wondering how I could add to it so it could actually work with spawning the thing I want where I want. Here's my spawning portion in my other script
if (mouseSystem != null && mouseSystem.activeSelf && mouseSystemScript != null && mouseSystemScript.enabled && Input.GetKeyDown(KeyCode.Mouse0))
{
Debug.Log("Landing");
Instantiate(Rocket, new Vector3(0, 0, 0), Quaternion.identity);
}
the other script is to big for me to send through discord
instantiate takes a position, instead of vector3.zero you pass the position you want
well you're spawning it at new Vector3(0, 0, 0)
in your update before you were setting transform.position to the mouse position. Here get it the same way but replace that new vector with it
uh. I think I know how to do that
You have everything you need at this point, you just gotta put it together now ^_^
So, would I pass the transform from MouseSystem to Landing System? and if so how?
make a reference
Yeah but it doesn't take transforms. I need vector3, and i cant convert transform to Vector3
Transform has 3 Vector3 properties though, and position is the one you want. So while transform is not a Vector3, transform.position is
ok I kinda got it. however im not sure how to resolve this
void Start()
{
mouseRef = GetComponent<MouseSystem>().mouse;
}
It looks like you are missing a component, it's not attached to the object you are trying to get it from
the script im trying to pull the data from
using UnityEngine;
public class MouseSystem : MonoBehaviour
{
[SerializeField] private LayerMask MouseLayer;
public Transform mouse;
public void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Physics.Raycast(ray, out RaycastHit raycastHit, float.MaxValue, MouseLayer);
mouse.position = raycastHit.point;
}
}
whoops hold on
and this is the gameobject its attached too
GetComponent tries to get the component from the object the script is attached to. So since you are trying to use GetComponent in a script called LandingSystem, that's the object it will look for
You can use a reference, like: [SerializeField] private GameObject myMouseObject; and then use mouseRef = myMouseObject.GetComponent<MouseSystem>().mouse; in that LandingSystem script
You should probably look into how referencing other scripts and objects in Unity work, it solves the vast majority of issues beginners have
so this is what i've got, ther error has gone, but it just doesn't work.
private Transform mouseRef;
[SerializeField] private GameObject MouseSystem;
void Start()
{
mouseRef = MouseSystem.GetComponent<MouseSystem>().mouse;
}
Did you drag the object to the slot in the inspector? (by the way, you can reference the script directly to avoid GetComponents, so [SerializeField] private MouseSystem myMouseSystemScript would work fine too
Well, if it's not throwing an error the problem might be somewhere else in the logic then, I can't take a look at it now, but if no one helps you I'll be back in a couple of hours
Do some debugging, like Debug.Logging the object that your raycast hits
If it even hits anything, that is. It could be null
Also make sure that you aren't mixing 2D and 3D physics, they can't interact.
Use Physics2D with Collider2D, and Physics with Collider (3D).
it is
@modern oxide You are still spawning at the zero coordinates, aren't you? Instantiate(Rocket, new Vector3(0, 0, 0), Quaternion.identity); that is your issue
No my problem is that its not spawning at the mouse, I know its tracking fine due too the green dot
Instantiate(Rocket, mouseRef.position, Quaternion.identity);
the rocket is simple
I'm guessing your animator is modifying its position
ughhhhAAAAAAAAAAAAAAAAAAAAA
5 hours
Now just gotta figure out how to make them land and actually stand upright and not clip
Here's the main function: https://hastebin.com/share/faziqewusi.csharp
Does anyone know an alternative to Application.dataPath? It works no problem when I run my project in Unity, but in the Build it seems to not do it's job.
I utilize the function in the link all over my project to access xml config files and image registries, like background layers. Speaking of, here's the two main functions that seem most broken (as in any calls to them in the build result in an error and the asset not returning): https://hastebin.com/share/izepacajil.csharp
This might just be a problem with the two functions. The issue blocks any further works on the project, it's pretty bad.
I have a weird problem. This code causes a huge white border in my game
using TMPro;
using UnityEngine;
public class DebugInfo : MonoBehaviour
{
void Start()
{
GameObject g_Canvas = new GameObject("Canvas");
Canvas c_Canvas = g_Canvas.AddComponent<Canvas>();
c_Canvas.renderMode = RenderMode.ScreenSpaceOverlay;
GameObject g_Text = new GameObject("TestText");
g_Text.transform.SetParent(g_Canvas.transform);
TextMeshProUGUI c_Text = g_Text.AddComponent<TextMeshProUGUI>();
c_Text.text = "Hello World!";
RectTransform rectTransform = g_Text.GetComponent<RectTransform>();
rectTransform.sizeDelta = new Vector2(300, 50);
}
}
If I comment the Start method, white border disappears.
If someone knows, please ping me upon reply
That's the canvas border gizmo. You can disable it in gizmos.
What is the actual issue? You jump from saying that dataPath is not working to suspecting some code, but never mention the actual issue and/or how you confirm it. Btw, dataPath works differently in the build. Refer to the docs:
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Application-dataPath.html
something Ive been wondering about for the longest time now, is there a better way to do this?
Do what?
Construct a color?🤨
set only an individual value of a color
Ah, swizzle the color channels? You could just reassign them via temporary variables, but that would be more code than just constructing a new color. You could implement Swizzling like in hlsl via extension methods I guess.
I cant directly change r.color.a but it's the only field I wanna change
A SpriteRenderer
Aah. Well, you can't assign it directly, because color is a value type property
You could do it like this:
var c = r.color;
c.g = gValue;
r.color = c;
But obviously it would be more code than just constructing a new color.
Code is not supposed to be beautiful.
Just clear and readable.
@fickle plume how do I make a model?
@nimble plinth Don't @ people not in conversation with you. This is a code channel. And is this a Unity related question even?
My fault
Yea
It it's
Cuz it's 3d
Modeling
And I wanna 3d model
@nimble plinth If you want to model in Unity, read pinned messages in #🛠️┃probuilder for resources.
Thanks
Might be better to learn a proper 3d modelling software, like Blender.
Next time, if you're not sure where to ask, ask in #💻┃unity-talk
Sorry, my bad. The issue is that textures and tiles grabbed with these methods don't work. On the left is the game run in Unity, on the right is the built one. Last pic could also be useful
The reason this does not work is because files in the build are packaged into a binary assets pack. Your XML file(if included in the build at all) would be in this packaged binary file, so you can't load it with a FileSteam like that. You could put it in Resources folder and load the same way you do load your other assets, but honestly, that's a pretty outdated way to load assets and is generally a bad practice.
And honestly, I can't see the appeal of using an xml for something like that anyway.
A simple scriptable object(or even a monobehaviour) with an array of tiles would be way easier to work with.
Do you know a video that explains this?
or something like that, I haven't really worked with scriptable objects
The docs/manual explains it pretty well. Other than that, just google or search on youtube. I don't have a list of tutorial links saved on my pc, if that's what you're implying. 😅
Basically, none of the raw files you put into your Assets folder make it into the game
Unity interprets them as specific kinds of Unity assets and lets you access those
unless they go into the Assets/StreamIngAssets folder and how you access them depends on your target platform
indeed!
How do I decide what should go in the StreamlngAssets folder?
Because I already use a Resources one
StreamingAssets is used for files that must be directly copied into the build folder
one intended use is for movie files
Based on these, which files should I move there?
the xml files?
If you want these files to be freely accessible and modifiable by players, then yes.
that's one thing. But will this fix at least a bit of this problem?
And is there a way to do this without making them accessible and modifiable to players?
It should. I've never used StreamingAssets myself, so can't say for sure.
Yes, as I explained earlier. Resources folder, a direct reference to the xml assets, or don't use xml at all.
I'll try the resources folder first. Thanks again for the help
If I really needed to include an XML document, and I didn't explicitly need to have the file on-disk, I would reference a TextAsset
The Resources folder will also let you access a TextAsset. It's special because you can load assets by name.
(and thus every single thing in a Resources folder always gets included in a build)
By the way, is there something wrong with xml files? Should I not use them in the full game once this prototype is finished?
I chose these because they seemed the most straightforward to use
Nothing wrong with it. I just think you're doing more work with it compared to other methods.
At least in unity. If it was a homebrew engine, tailored for one specific game, it might be fine.
In unity we have Scriptable objects for storing arbitrary data.
I keep most of my configuration data in ScriptableObject assets
I get to directly reference these assets where I need them
Does that work for bigger games as well?
I mean I hope it does 🍀
Sure, why not.
An XML/JSON/YAML/etc. document doesn't give you that same certainty.
The scriptable objects are looking great from what you're saying. I'll use them for the full thing
Some may be using an xml under the hood, but they would probably be serializing/deserializing them automatically into a scriptable object at editing time.
that sounds mildly scary
I don't have concrete examples in unity, but I've worked on an unreal game that does that. But I believe it was mainly due to the fact that it was developed in a custom engine before moving to unreal.
in unity editor game looks like first image
but when i build the project and open it, it looks like poo like second image
not sure why its doing this probably something lighting related but if anyone has a fix can you please help me
They had all kind of weird authoring tools.
there's one advantage to their XML/resources approach, because it's always loading only the necessary assets at the time
this would require more effort with scriptable objects probably
this is something that addressables solves nicely
Indeed. That might be one reason, though addressables adress that I think.
this was an actual issue that I had in a bigger game 🙃
Make sure you're using the same quality level in the build as in the editor.
Can anyone recommend a complete tutorial on YouTube that teaches how to program in Unity?
google.com
Don't be lazy and do your own research. That's the first step to learning programming properly.
In the build version physics are completely messed up. Running a dev build shows no errors, though.
In Unity everything works properly once again
One common cause is your physics/movement being frame rate dependent. Build usually has different frame rate compared to the editor.
Not like that. Moveing left and right works just fine, but instead of jumping, the player starts a jump, stops after like 5 frames and stays midair, able to move left and right
I'll record it once I figure out how to run a build in windowed mode
Well, then it's the jumping logic that is the issue. You'd need to share the code.
private void Jump(float height) {
velocity.y = Mathf.Sqrt(2 * playerVariants.gravity * height);
ParticleSystem jumpParticlesInstance = SpawnSimpleParticle(jumpParticles1, Vec3ToVec2(bottomColliderPosition), true);
ParticleSystem.ForceOverLifetimeModule forceOverLifetime = jumpParticlesInstance.forceOverLifetime;
forceOverLifetime.enabled = true;
forceOverLifetime.x = velocity.x / 5f;
jumpBuffer.Clear();
}
```It's just the top line.
Here's the full code, most of it is just variables at the beginning: https://hastebin.com/share/wubigijude.csharp
I think I'm creating more problems than there initially were
- Why the heck is it a particle system?
- Share long snipets of !code via a paste site:
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Yeah for some reason when pasting the hastebin link it also pasted in the contents as text
the particle system is just for effects
nothing to do with physics
Oh, didn't notice that.
how can i change it to the same
It's very hard to follow your code.
Honestly, I don't see how you're moving the player in that code. You're only using the velocity to move the particles.
In the quality settings you can set the default level for each platform.
if this is it they are the same yet it still happens
Yeah. They seem to be the same. Then the issue is something else.
shouldi try putting all of them to something higher or what cause they are the same both editor and build quality
yeah idk its a bit weird
Yeah. Try setting them to ultra just for a test.
alright i get back to you
I don't see a rigidbody used in that script at all.
ok yeah thanks apparantely that fixed it
now the build quality looks the same as unity editor
i dont know why it was different though before but atleast it is working on ultra
thank yo uso much
I think your editor was using ultra. You can see it highlighted compared to other options:
#💻┃code-beginner message
yes
So I have these few lines in a function of mine:
// Load the UXML slot template for individual characters
VisualTreeAsset slotTemplate = Resources.Load<VisualTreeAsset>("UI/CharacterSlot"); // Adjust file path/name as needed
if (slotTemplate == null)
{
Debug.LogError("CharacterSlot template not found in Resources/UI folder.");
return;
}
// Clone the template for the slot
VisualElement characterSlot = slotTemplate.CloneTree();
Debug.Log(characterSlot);
And the attached image is the hiarchy I'm working with. I don't understand why the debug message shows that the width of the cloned element becomes NaN instead of its set value.
Checklinearoffset and alignlinearoffset are not in the script you shared.
I only see them getting called
Did you leave out the part that actually moves your character..?
No, I forgot to add these two:
Goddamit, I've no clue how you came up with an idea to name a method that actually moves your object Offset()
I'm sorry, but I'll just have to pass on your question. That code is unreadable and almost undebuggable.
Yeah
Started with sticking to walls, now the configs won't load properly and there's more stuff stemming from all that
might need to start over the project
I'd recommend looking up some sample code from other people projects or tutorials(unity learn could be a good source for that) to get an idea of how similar features are implemented.
As well as maybe ask for a code review before your code is beyond redemption.
where can I ask for a code review?
Here. Though maybe keep it a bit specific instead of sharing your whole project code.
Why is everything virtual and protected?
You could for example, describe the overall logic/idea behind your code. And ask if it's okay. Followup questions might follow.
Honestly, I'm not sure what this script's purpose is? The name of the class and methods inside don't relate or tell me what it's supposed to do . . .
It was meant to be a default class for every object in the game. I don't know how else to do that.
From my experience, you don't need a base class for all objects. It's bad to have an inheritance chain for all objects. Utilize composition over inheritance
Also, gameObject is already the base class for all GameObjects in Unity . . .
i have made everything how i would like but my camera just looks glitchy when i move it around
I mean I need a few functions that can be called at any moment
I thought a Utils singleton, like my CameraManager (CameraManager.Instance.ShakeCamera and so on), but I feel a weird disgust towards the .Instance part. But that's just me
We understand how third person cameras work.
We don't necessarily know how your camera works.
If you have a code problem, feel free to explain it and share your code.
i have a screen record of how my camera looks like i can send that and i can send you my code
You can use static classes/methods, extension methods, or interfaces to accomplish that. It gives you more modularity and separation than tying a base class to everything . . .
In case you need to know, I spoke with my teammates and we're remaking the prototype
so this is a script i have on main camera
and this is how it looks like\
it looks like it is not syncronized with player
Can someone help me with this ? I'm following a tutorial and when I tape spawnPipe in start unity tell me that it's not asigned so what should I do
Uhh... anyone?
It's best to post the error message for us to see because we don't know what is not assigned, and make sure you followed the tutorial correctly. It says it's not assigned, right? Did you assign it? If not, check the tutorial and look when they assign it . . .
Maybe ask in #🧰┃ui-toolkit
okay
You'll find better help in #🧰┃ui-toolkit
Here it is
can you help me with a camera problem friend?
put the function Spawnpipe outside the Update function
you probably should 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
• :question: Other/None
Anyone know why the jumping feels higher each time I jump?
post your !code correctly and someone might
📃 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.
Thank you for you're reply
How I properly implement github with a unity project? I keep getting file too large warning even though i aleady put in ignore and attribute files.
You've already created a commit with the entire Library folder stuffed into it
Adding a .gitignore afterwards (or even adding it after staging your entire project) won't help. .gitignore only stops you from staging new files.
I created a repo inside a unity project, dragged in both files and then ran "git add ." and git commit
That means you put the .gitignore in the wrong place. Where did you place it?
It should be in the root of your project
directly inside the project folder
oh
undoing the commit will allow me to use those ignores right?
ok i think it works now, only 65 changes
I'm not sure what "Undo commit" does in Github Desktop
if it creates a commit to revert an older commit, then that will not help
tbh I'd just delete the .git folder and set it up again
It worked i think, only 65 changes and now i can push
the Desktop GUI doesn't let you do much
oh, interesting -- maybe it recognizes that you didn't push that commit yet
If you've already pushed the commit to the remote repo, then just throwing out the commit is problematic (your history now doesn't match the server's history)
git is annoying when it doesnt work xd
I decided to create a game with friend (godot) and every time there was a conflict he would just press the force push button
xD
"revert changes in commit" does that, I'm not sure what undo does
Hello. I've made a caracter movement script and everything works fine, except the character cannot jump. I am using the "new" input system
void Update()
{
MovePlayer();
SprintPlayer();
if (IsGrounded())
{
JumpPlayer();
}
}
void JumpPlayer()
{
if (IsGrounded() && canJump)
{
canJump = false; // Prevent double jumps
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
StartCoroutine(ResetJumpCooldown());
}
}
IEnumerator ResetJumpCooldown()
{
yield return new WaitForSeconds(0.2f); // Cooldown duration (adjust as needed)
canJump = true; // Reset the ability to jump
Debug.Log("Jump cooldown reset, can jump again!");
}
// Helper function to determine if the player is on the ground
bool IsGrounded()
{
return Physics.CheckSphere(transform.position + Vector3.down * 0.5f, 0.1f);
}
this is what I am using for jump mechanic
Ah! Then yes, that's a different operation
is JumpPlayer running?
[car crashing sounds]
been there lol
it's not leaving the ground
but is the code running? you should use Debug.Log to see if that function is going off anywhere
At current, you're running JumpPlayer() every frame the player is grounded, it doesn't seem to be using the new input system at all, or any input system really, unless you're hooking it externally
if it was git bash you could just git rm * && git add .
you should also make sure canJump is true when the script starts, otherwise there will never be anything to turn it true
yeag
Then amend
the method works without the condition
I have that condition because I want it to jump only once
well..you'd want git rm --cached (:
git rm would remove the files from the working tree. bye-bye project
using UnityEngine;
using Unity.Cinemachine;
using System;
public class FreeLookRightClick : MonoBehaviour
{
public CinemachineInputAxisController axisController;
Vector2 mousepos;
void Update()
{
// Save and restore mouse postion when exiting look around
if (Input.GetMouseButtonDown(1))
{
axisController.enabled = true;
mousepos = Input.mousePosition;
print(mousepos);
Cursor.visible = false;
Cursor.lockState = CursorLockMode.Locked;
}
if (Input.GetMouseButtonUp(1))
{
print("released");
axisController.enabled = false;
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
Cursor.SetCursor(null, mousepos, CursorMode.Auto);
}
}
}
does any1 know how can i fix it so that when I release the right button and it unlocks the cursor, that it snaps back to where it was originally locked?
short answer = no. long answer = the input system can do it but it's usage is limited (https://docs.unity3d.com/Packages/com.unity.inputsystem@1.11/manual/Mouse.html). you could just hide/show the cursor but then it won't be locked to the screen and could move onto another screen. one option is to do it all yourself and don't use the Cursor class.
For cursor warping support you will need to use the New Input System
how can i do that
do what?
Do what
Install it, read the instructions, look up and read the documentation on Cursor Warping.
if you want to do your own cursor then research 'software cursor' or 'custom cursor'
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.11/manual/index.html - is it this? I cant find anything about cursor warping
Hi, just want to ask some experienced guys for some advice. I have just started my journey in game development, I have basic programming concepts, but I am still not very familiar with the principles of oop and basic api unity. I start with small projects, but my friend suggested to create a merge game like marge mansion, can you tell me if I should take on this project, or continue to create games on a couple of gameplay mechanics to learn how to use unity and learn how to program?
Start small and !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
the link i gave above
ty
Hello, I have a little problem, in my Unity game I'm trying to make a pause menu.
I managed to do it without any problem, but my only problem is that my turret can still shoots in the pause menu. I've already tried several things, and I managed to make it not move in pause menu, but the problem is that now it just can't shoot at all, so I'm desperate since I'm really not good at programming...
Here's the code of my player/turret :
https://hastebin.com/share/oveqekixah.java
And here's the code of my pause menu :
https://hastebin.com/share/uxaheyahah.csharp
At the bottom of this page
https://docs.unity3d.com/Packages/com.unity.inputsystem@1.11/manual/Mouse.html
that code looks fine, gonna need to see the gamemanager code as well
Thank you for looking ! And here is my game manager code :
https://hastebin.com/share/nejihaxodo.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
move FpsCap into it's own file or move the code in FpsCap.Start() into GameManager.Start()
either set break points and see what's going on or add several Debug.Log() statements
Dont see anything obviously wrong. I would log the InstanceId of gameManager and pauseMenu here
void Update()
{
if (gameManager.gameOver == true || pauseMenu.isPaused == true)
return;
Movement();
FireMissile();
}
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #🔎┃find-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
I'm making a top down online fighting game, but I want the weapon to rotate to the mouse of its owner
But if I put that in my game manager, how will he know what Movement and FireMissile are if the code for those things are not in that script ?
How can I make it?
I said to log the instanceid's in that code, not move it
Oh ok, I wasn't sure I understood, thank you !
It's just a sanity check to make sure you are really looking at the objects you think you are
Debug.Log($"Game Manager {gameManager.GetInstanceId()} {gameManager.gameOver}", gameManager.gameObject);
If you are a beginner I would refrain from doing multiplayer games, but you could just get the mouseposition and just get the direction from the mouseposition to the player and with that just rotate the weapon to that direction.
I don't know how to use the new input system so that's why I linked the old input systems documentation (there is probably something similar in the new one).
Thank you for your advice, I'll search how to get the position of the mouse and rotate the weapon
The documentation I linked shows you how to get the mouses position using the old input system, so that should be a start.
make sure that u convert the mouse position to world-space
yup I totally forgot
I used a dontdestroyonLoad for my highScoreTable in my game which normally is being shown on the main menu to display the scores of player. I implemented the dontdestroy so I could access the addHighScoreEntry method, which I have added as a compnent to a gameobject with text and templete for entries. ( I followed a yt vid for the highscore table). However, when using the dontdestroyonload, the highscore table is visable in the game scene and I can add entries to it since it is loaded. Is there a way I can hide the scoretable when the game scene is runnning or should I use another way to access methods of the scoretable gameobject?
thanks in advance for anything that help 😄
deactivate the game object if you don't want it to be rendered
Can I still accesse the methods in it?
Sure
Disabling a behaviour just means Unity won't send some messages to it, like Update
Would you suggest a separate script like a sceneManger or how would I implement it?
(and deactivating a game object disables all of the behaviours on it)
It sounds like you should separate the thing that stores high scores from the thing that displays high scores
The tracker always exists. The display only sometimes exists.
I probobly should
Anything wrong with applying Singleton to interactable objects? Like, I need a special cursor for my game, and obviously it's preferred if there's just one, so would there be something wrong with adding a static Instance to the Crosshair class? Interactable as in it plays a big part in the game
The only consideration for making something a singleton is whether exactly one instance (no more, no less) exists at all times
I'm not sure why you'd want to access a crosshair statically, though
How else could I do that? Finding it by tag name each time I need it feels wrong
I'm just wondering why you need access to it.
Do different objects need to change its color when you hover over them?
Hey guys I want to add ragdoll physics to my game, I’m sortof wanting the character to perform an action such as swinging a sword, but they can be knocked around during the animation by enemies, or if they run too fast into an object, where should I start
Objects need to access it's position, some other properties, set input buffers and all that
it's a mouse only game
And I was thinking of making damage based off the velocity of the weapon when it collides with enemy object
I also want my character ragdoll to be able to trip if they run too fast into a curb or something hahaha
input buffers..?
@pulsar birch i think you may also have to configure your !ide based on that limited screenshot from the other room
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
also @pulsar birch why don't you declare variable "p" as Vector2?
Just, all sorts of stuff
i was wondering the same ^^
im making a flappy bird game just to learn basics and i dont know where a lot of things go. this is what its doing and i don't know how to fix it
dont mind the terrible art
without any other code i dont know what your issue is
hold on
your code snippet only shows you trying to cast float as an int
can you help me real fast
out of everyone you could ask i am the worst one
i think you should do timer + (1 * Time.deltaTime)
lemme look at the rest
I meant sunny
just ask your question
Don't ping random users. Ask your question and people that are able to help wiill help. #📖┃code-of-conduct
do not direct people
What's the issue?
@burnt vapor this
you could try implementing a spacing variable and making sure that the distance between pipes is that spacing
if thats ur issue
i think their problem is with how close the pipes are
What other way could this be done
I don't feel like doing guessworking
How do I make the ui look like the bottom right photo
my issue is the spacing and the fact that it doesnt have random placement on the Y axis (i think its the Y sorry if im incorrect)
This is a coding channel. #📲┃ui-ux
this is coding
but like
still
your code doesnt implement random spacing on the Y axis i think
Because by what you and Fen are saying I feel like this is a very awkward way to do this
!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
the two ^^ indicates it was referring to the message Two up from mine, which was from someone else 🙂 i was not addressing your comment
the thing i i dont know how to make it random
alright, mb
or where to place the code to make it random
What are you talking about? You are asking how to make Visual Studio look like Jetbrains Rider? This has nothing to do with actual coding
you could set the Y offset to Mathf.random and some range
stop
Math.Random
and i also need a scale of what the Y can be equal to to make sure it doesnt completelt disappear offscreen
ohhh
mb
!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
look here
thx
If this is a question on how to set up your editor, then follow the links. Idk what you mean with making it look like the bottom right window
they wanted their ide to show code like the bottom right window
But please feel free to clarify if this is an actual coding question
It's okay I got it!
The editor on the bottom right window is not configured either, so idk where you got that idea from 😉
It would help if you properly shared the code using a paste site 👇 . The last screenshot is cut off
📃 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 don;t have the same options
i included a 3rd photo containing the rest i thought?
no external tools
You need to follow the steps by the bot, and it will become available
here
Especially installing the workload, then setting the external editor.
If this is about the Y spacing, then note I don't see the Y position being modified at all
Just the pipes moving left
hold on
It's the first step
heres the script that continuously spawns them
lets say the default Y position for the bottom pipes is 0, you could set pipe.transform.position = new Vector2(x, Random.Range(0f, 10f)) (pseudocode)
Installed through Unity Hub or did you install Visual Studio manually?
unity hub
what does the f mean next to the 0 and 10?
use #💻┃unity-talk or something this isnt a code question
Means the number is a float.
float, it has to be a float or it wont be inclusive
This is a coding concept and therefore valid for this channel, you don't have to tell me what's valid in this case
alright
where do i put the line of code though?
you could use an integer, and then -1, 11 which would give values from 0 to 10
up to you, wherever you instantiate new pipes i suppose
Instantiate takes a position parameter. You set it to transform.position, but you can also add * Vector2.Up * Random.Range(...) here to offset it with a random "Up", or Y value
Use that for randomization
What ends up happening is that you set it to a random Y value based on the value passed in the Random check, and this is basically added to the Transform's Vector value through multiplication
do i put it in between transform position and transform rotation or..?
Essentially a bunch of compact code, you can also write a variable before instantiating which might be more readable
So if that's confusing, maybe do this instead
No, you update the second parameter with this multiplication
The random range indicates the offset of the pipes, try it
im dumb
it is installed
still no work
You're better off installing Visual Studio manually rather than through Unity. It's a lot less work
kk
brb
and what do you mean when you say "parameter"
I mean'
everything within the brackets is a paremeter
ohh ok
It's technically an argument, but it means values passed into methods
Instantiate(param1, param2, param3)
You pass arguments into method parameters
so like this?
No, now you just multiply the result of Instantiate
You update the second parameter, not the return value
you have to put those vector math inside the position parameter
Instantiate(pipe, transform.position * Vector2.Up * Random.Range(0f, 5f), transform.rotation)
If this is confusion, perhaps it might be a good idea to do c# tutorials before undertaking actual Unity. It's not a good idea to take on a Unity project without any C# experience
im sorry for being stupid when it comes to this but i dont know what return value even means
!learn perhaps? (i didn't mean that sarcastically i was doing the command for the link below)
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
i was following a C# tutorial and it did this
Programming is a big thing, you should not do both the Unity framework and the C# language
Especially because Unity is massively different when it comes to how C# works
try learning c# from -> https://learn.microsoft.com/en-us/dotnet/csharp/
it's very beginner friendly
I would advice you check the pinned posts for tutorials
Vertx listed a good intro to c#
So is it this?
objectPropertiesRef.buildingType = "Wall";```
Attempting to access a script component on an object that I am creating during runtime, and change one of the script components properties.
Not entirely sure how to do that on unity
Why are you using Component on the left? Use the actual type you care about
How would I go about using Mathf.Lerp in this situation? I want the distance to interpolate smoothly
float calculatedDistance = Mathf.Clamp(camDistance + Mouse.current.scroll.y.ReadValue() * -1f * Time.deltaTime, 4f, 15f);
camDistance = Mathf.Lerp(camDistance, calculatedDistance, camDistanceSpeed * Time.deltaTime);
Why would you multiply scroll.y by Time.deltaTime—it's instantaneous input, if you scrolled 3 units on one frame that's the distance you scrolled, not that scaled by the time it took for the frame to render
Oh you're right, that makes no sense
What can I replace GlobalFunctions.Instance with here? Right now this code won't work unless a GlobalFunctions object is created, but what I'd really need here is a way to have these functions be accessible without the need for an instance.
GlobalFunctions -> https://hastebin.com/share/cibedipino.csharp
Crosshair (Use case: line 33) -> https://hastebin.com/share/uqatozobuc.csharp
these functions can just be static, you don't need a singleton
as the function is self-contained
No need for a scriptable object either
Just a Script file with these functions set as static?
Yes. A static method is not associated with a specific object instance (just like any other static member)
I figured it out
How do I get my asset that I spawn in game to snap to the ground instead of clipping half way through it?
If the model's origin is in the wrong place, I'd suggest parenting it to an empty object
Adjust its position so that it lines up with the gorund
Also make sure the rotation and scale look right when the parent has those set to default values
(no rotation, 1 scale)
got it thanks!
that's a bit vague..."call a button"?
do you have a Unity UI button that you want to click via a script?
yeah thats what i meant
hm, I thought there was a nice Click() method!
The less enjoyable alternative is just calling OnSubmit directly
It needs a BaseEventData. It doesn't require any actual information, so you could just pass it a new one
BaseEventData data = new(EventSystem.current);
button.OnSubmit(data);
Manually calling OnSubmit is equivalent to hitting "enter" with it selected
grumble grumble! it's private!
You could also call OnPointerClick, but that wants more complex event data (that includes which mouse button was used)
my teacher taught me how to use one of the methods, but I forgot everything
we made a button variable i think
are you sure you aren't trying to respond to a button being clicked, though?
then we made like an on button press void or smth
i.e. run a method when the button is clicked
that's what im trying to do
I thought you were looking for a way to trigger a button press from a script
In that case, you just need to add a listener to the onClick event
that was what i wanted
Any method that takes no arguments and returns void will fit in there
button.AddListener(SomeMethod);
imma dm my teacher as well, but i'll try this
hello, im making a doodle jump clone and i want to know how im supposed to spawn platforms that have springs on them + other different types fo platforms? right now i'm only spawning one type of platform which is the very basic one that does nothing
heres a ref of what im looking for for clarity. right now in my game, im only spawning the basic paltform types (the green ones)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
The Unity tutorial straight up told me to use ChatGPT🤣
Looks pretty good tho
If I wanted to read about each function in this code where would I do that? Is there an official Unity documentation?
!docs
How do I find a specific function there? For example transform.rotate
There is a search bar
Important, no. But it never hurts to familiarise yourself with them to see what something is able to do
And it’s just a matter of remembering?
I wouldn't think of it as an exercise to make sure you remember everything you read
You might stumble across something that you realise could work to help you do something in your game
Hmm, how do you find what you need in the documentation? I searched “jump” for example and it doesn’t seem to show the results I’m looking for
That'll be done with a rigidbody that gives physics to an object
Yes but I meant just as an example, to see if I could find answers in the documentation
It only gave me things for 2D
Programming API's/documentation is important be able to read but It's not going to tell you how to implement something (there are guides and tutorials for that) but what the documentation does do is provide you with a list of methods (for Unity in this case) and as a developer, you can look up these methods and see how they work and what parameters/overloads they take. For example, if you're making a jump mechanic and you want to use the "AddForce()" method that the Rigidbody provides, the documentation will show you how to use it
I find it's about breaking down a problem in a way that could help you find something in the docs. It's hard to explain.
Take jumping. Taking it down to the simplest form, that's like a bunch of force has suddenly pushed you into the air. Searching jump doesn't give anything, but the more technical "force" will. And AddForce sounds like what jumping is if you didn't describe it with the word jump
And you want to use addforce, so you can see what allows you to do that, and now you have the knowledge of what rigidbody would be used for
Ohh I see, so basically you can’t directly learn from the documentation it’s just like a collection of functions
I wouldn’t think of it as a force so that’s tricky, like if you asked me what jumping would mean to me in the most basic form I’d say that it’s the y value changing
So how do you initially know what words to look for? You just search the problem you try to solve on google?
Experience plays a part, it takes time to get a feel for how to break down your goal into the steps you can create
That’s true, I always hear that coding is about breaking a problem into steps and first making a logic map of solving the problem
I’ll try and work on that
google and documentation
This largely come down to experience but searching problems can help a great deal. You don't have to memorise the whole API but having a good understanding of what the problem is can help. Programming in a nutshell is just solving problems, so being able to break down and understand the problem you are trying to solve is half the battle
The Unity guide broke the code into steps pretty well
documentation is not supposed to be used as google where you search "jump" and it will tell you how to do such thing, it's only purpose it to inform you on its API and components/tools that you can use
I see, so you need to specifically know the tool’s name and the documentation is to explain how to use that tool
you don't need to know the tools name specifically, you can search for all of the tools it provides in it and search for something you can use.
yes it should tell you how to use that tool, or what it does at least
I see that makes sense then, that’s why I couldn’t learn from documentation and gave up before haha I used it wrong
Documentation is essentially just a list of methods/functions that Unity (in this example) have created. Unity has exposed a collection of methods that you can use in order to create your own systems. An example would be if you wanted to make an interaction system for your game, you can use a Raycast. The Raycast is something that has been implemented and exposed by Unity, hence you can read how it works in their API/documentation
I tried SFML and it was so difficult 🥲
If you would like to know how something is done, for example a jump, you would look on google or youtube
Ohh I see it’s a showcase of their library
Exactly
That's what documentation is really
Hopefully they specify for which Unity version it is😅
It's describing how you as a programmer would interact with their API/engine
It should be kept up to date for the most part, if there is anything that had changed, the documentation should reflect that or they will mark a particular function/method as "deprecated" if they want you to use another alternative
The API and Manual does show which version of unity you are currently browsing on, it is not really needed to tell you what version of unity you are on unless there would be some breaking changes to the component (usually it is just some deprecated stuff and or renamed things)
for instance, unity 6 renamed RB.velocity to RB.linearvelocity, both are the exact same function exept for the name change
Well for example I noticed that “Mouse” is not an Object anymore when following a YouTube tutorial and trying to detect a mouse click
It was Input.Mouse something and it was marked as an error on my end
Mouse? That is not an object afaik, you would do Input.GetMouseButtonDown(1) or Input.GetKeyDown(Keycode.Mouse1)
Yup! That’s what worked for me afterwards, and then I just abandoned the video because following it was so confusing with the outdated changes🥲
When working with the input system, I recommend working with their new input system (I guess standard now?) over their legacy input system, it is a bit different but It is a better system and It's also what Unity recommends
Ohh that explains it, they made a new system for it
I never learned it lol
the old system still works, it is not deprecated yet
Hmm maybe it was a mistake on my end then
It's not deprecated, both work but when working with the legacy system you would usually do something like "Input.GetMouseButtonDown(0)"
You would also need to wrap that in some sort of conditional(if) statement
For example:
Oh wait what I saw in the video was
“Mouse.current.leftButton.wasPressedThisFrame”
And then it didn’t detect what Mouse is
if(Input.GetMouseButtonDown(0))
{
//Left-click pressed
}
Yup that’s what he did in the video but with the line that I wrote, and it didn’t work but the one you wrote did
this is how you manually poll the mouse using the "new" Input System. if you are not using that and don't have the package installed, then naturally that would not work
Ohh, you need to install something else for that
This looks easier lol
if you aren't using Unity 6, yes. it is installed by default in unity 6
Oh I am using Unity 6
then you either uninstalled the package, or your IDE is not configured so you didn't automatically add the using directive when attempting to use the Mouse class
Funnily enough the guy in the video wasn’t using 6 lol
the input system has existed for years, it is not exclusive to unity 6
Wait so which is the new one🤣
He may have had the package installed though, as you could install it in previous versions of Unity
It's the "newest" one, but it's hardly new.
At this point it's the standard, and the Input.GetKeyDown method of input is the old one.
Ohh hold on is that the
using UnityEngine.InputSystem;
Because that also gave me an error
the input system. the one the video was probably teaching you about. it's just "new" in that it is more recent than the legacy Input class. but it's still like 6 years old at this point
Huh, so maybe mine wasn’t installed automatically
Check your package manager to see if it's installed
unless you are using a project that was created in a version before the first Unity 6 LTS (though there were several preview versions that had it installed too, i just dont' know the specific patch number that did it) then it was installed automatically.
https://screenshot.help
also it's there in the screenshot
You could also go to your preferences > Player and see what input system is ticked, you have an option of "new, legacy or both". I'm not sure if Unity 6 is different as I've not upgraded but I know there is an option in the preferences to choose which input system you use
I believe it is on both by default
Ah, that's fine then
this does not indicate whether the package is actually installed
and that setting also does not affect compilation
Is there even any benefit from using the new one because visually I understand the old one better
True, I just thought of it as an option to try if it turns out the package is already installed
you can use whichever you prefer, but the input system is a more robust and extendable way to get input. it handles different input devices better, it is much easier to remap controls, and you can write cleaner code with it if you go with the event based approach rather than polling the input manually
you can use the old or the new one, all they do is supply inputs so either or will be good
but yes what box said
I see, I’ll just stick to the old one for now since I’m just learning how everything works haha
That's fine
Yes, the newer one is much more flexible, it is a bit more complicated in some areas because you need to do some extra steps with actions maps and it is event-based but this means that it is a lot more powerful. For example, you could have multiple set of controls/actions (UI controls, gameplay controls as separate "control schemes")
I only understood half of this😅😅 I don’t have much context for many terms haha
I have not even learned the new one yet and it's mainly to do with laziness but there are improvements with the new one over the old one
It also is geared up for different input types (mouse, keyboard, gamepad, haptic devices, AR/VR devices) and it handles re-mapping of input, so It's definitely something worth learning but if you are completely new then it may make sense to stick with the legacy until you need something specific that the other input system has
Ohh so it’s good for like multi platform
Yes
Like if you want to convert a game for multiple devices
I see
Thank you for the help and explanations guys🙏🏻🙏🏻
hello, im making a doodle jump clone and i want to know how im supposed to spawn platforms that have springs on them + other different types fo platforms? right now i'm only spawning one type of platform which is the very basic one that does nothing
heres a ref of what im looking for for clarity. right now in my game, im only spawning the basic paltform types (the green ones)
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
doodlejump probably just randomly spawns them with different weights
and probably takes into account score/height
wdym by different weights?
suppose you have a box with 2 blue balls and 8 red balls
if you pick one at random, you have a 2/10 chance to get blue, or 8/10 to get red
so you could say that blue has a weight of 2 (or 0.2) and red has a weight of 8 (or 0.8)
that affects how common or rare each type of platform is
you obviously wouldn't want equal amounts of every platform
step back from the code for now; code is how you do it, but first you'll have to decide what you want to do
start designing what types you want to have, how common you want each type to be, and how that changes depending on score
once you have a good idea (doesn't have to be a complete idea) of what you want, start coding it up, and if it's not complete or not to your liking, go back to tweaking the design
that's really good advice, thank you!
Anyone know if its better to split up different aspects of my player into different scripts? Like if i wanted to add a player pickup should that be in its own script and then the player inventory be in another script and interact be in its own script? Also how should i go about doing raycasts for different things using the same key? I wanna have a pickup system that casts a raycast and picks up the item when i press E, and also use E for an interact raycast that will see if i interacted with any interactable objects like crafting benching and light switches? Can that all be done from just one singular raycast?
definitely split behaviours (actions) into separate scripts. that's unity's strong point; it known as composition (over inheritance) . . .
basically, to create specific objects in your game, you want to build them by adding components to the GameObject. those components are individual behaviour that make up what the object is and does . . .
it's a component-based approach using composition . . .
Depends. I wouldn't put pickup logic in a different script. Maybe in a non MonoBehaviour class if I have some kind of actions system and pickup logic being one of the actions.
Inventory, perhaps. Although, again, I'd rather use a plain class for it.
Think of the class - does it need any of the MonoBehaviour functionality? If yes, then it can be a separate component.
Regarding the interactions, I'd implement them on the interactable object. So that interacting with a pick-up object would I initiate pick-up, interacting with a crafting station would initiate crafting, etc...
So yes, the raycasting logic on the player would be the same, regardless of the interactable object.
So i'd have like a script on my Items and on that script there would be a function called pickup or something and i would call that from another script with my raycast?
and same thing with my crafting benches and stuff? like a script on the crafting bench with its functionality and then a function for Opening or closing the crafting bench which is called from the raycast also?
Yes. A function called Interact declared on a base class or an interface.
ideally, an item (GameObject) that is interactable would have a script that implements an IInteractable interface. you'd have a separate script handle the raycast that checks for the interface. if an object is found, you call the Interact or Use (whatever method) you choose to call it
each script with the IInteractable interface must implement that method, and will have its own code . . .
Think of what the player is doing. It just initiates an interaction with an object, regardless of what that object is. It doesn't need to know anything about it. Now the interaction itself depends on the type of the object, so it can be implemented on that object.
the Interact method implemented on a light switch script will have code to flip the switch (turning it off or on) . . .
the Interact method implemented on a crafting table will initiate crafting mode and pop-up the crafting menu and possibly open the player inventory, etc . . .
Ok cool so i guess its pretty much the same thing as Unreal's blueprint interface system, i used that a little bit and it seems pretty similar.
So to make sure i got this right, I'd just have like a script on my player that is called PlayerInteract or something, and that will have a method on it to shoot a raycast when i press a key. And in the raycast it will check if it hits an object with the IInteractable interface and if it does it will call the Interact or Use method on the gameObject that was hit?
It's a common way to implement interactions regardless of the engine or programming language
yeah, the raycast can check for GameObjects on the Interactable layer. if found, get the IInteractable interface from the returned (hit) GameObject and call the Interact method . . .
I personally prefer to have a CharacterController kind of class implementing this and quite a bit more functionality, but it really depends on your project. In my case it makes sense, because I'm working on a sort of crpg game similar to Neverwinter nights, so there would be a lot of core functionality that all characters and their variations would have.
In a more modular game where you'd want to enable disable core functionality like interaction and such, it might make sense to separate it into a separate script.
Ok, well thanks for the help guys! ill be back again if i get stuck on something with it, but i should be good to just lookup stuff about interfaces within unity now to see exactly how to do it
Interfaces are not really a unity thing. It's a C# feature(and many other languages have something similar).
yea im still kinda a beginner to learning programming with an actual coding language in general, i tried doing unity a while ago and kinda lost motivation and then switched to unreal and blueprints, but now I'm back to unity and actually more motivated now to get better with it
felt like i just wasn't really learning the core concepts well not learning with an actual coding language and it felt like a waste of time lol
trying to play a video in unity but the quality looks much worse than the source file, anyone know how to make it perfect?
do yall know if theres a good course for procedurally generated stuff in unity?
The internet is filled with tutorials on procedurally generating stuff
- It's not really related to coding.
- You'll need to provide some more info on your setup.
yeh sorry, its just the videoplayer component, i thought someone might know off hand if its capable of playing good quality video at high frame rate(1920x1080 mp4)
Whats a good youtuber to learn c sharp off?
It should be able to play whatever resolution it is at reasonable frame rate(think same as any other video player on your PC or the target platform).
free code camp has a good 4 hour beginner course
Ok thanks.
yeh i thought that too but its not the case
It is the case. If it doesn't work for you, you'll need to share more info/context on your setup, as I said earlier.
At the very least take a screenshot of your video player component
Where does it output the video to?
Take a screenshot of the video clip asset inspector as well.
For random spawning I suggest you update your prefab into a list or array of gameobjects that define the platform gameobjects to Instantiate.
Then just randomly pick one with a weight system
As for detecting what platform you land on, check collision when landing on them and use pattern matching to pick the type of platform you land on. For this I suggest you either use a tag, or you create an interface that specifies a property to be implemented representing the identity.
Next, another interface that represents the action to visualize when jumping on them. For example, the spring expands. The reason you also want to use an interface is because pattern matching is very easy and it works with GetComponent.
Lastly, the breakable platforms should be a trigger instead, so falling is not interrupted.
Hi guys i am an absolute Beginner and faced to an issue i don't get. I opend a new 2d projekt to test a bit around i created an canvas , as a child i created an image. I moved an png file for the Backgroud . And yesterday it worked fine i saw the image in game and scene view . Today i played around with some buttons and hooks and then i lost my background only on scenview. I can see the borders and a black diagonal line . I csn move the image and i see that it moves in game view. Icreated a complete new 2d projekt and have still the same issue. I asked chat gpt for troubleshoot my problem but all tasks are correct. Any thoughts?
so i having problem with movement, but all works except it's little bit slippery who knows why is that:
Please use proper !code formatting when posting here
📃 Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
ok that was embarrassing, I placed a little bit down capsule and ray cast works for now👍
Im about to go insane. I've wrote a script that displays an interact Icon when you're near a Interactable object, specifically doors, however it's only at some of the doors it will correctly displaye " Press E to interact " once you're close, even though they have the exact same settings and components( at least i think so). Any ideas ?
You'll have to show the script
Sure, but doesn't the fact that it's the exact same scripts that are attatched, and only one is working means that it's not a script or code issue `? sorry if it's a stupid question, but im new to game developing
There is something different in those two cases and seeing what the script does would give hints at what to check next. It's impossible to guess what might be wrong just by looking at two identical screenshots
Makes sense. here is the script that each Door is inheriting from, and ther door script
Does pressing E still work even if it doesn't show the text?
Yeah. E will still make you interact, the icon just doesn't show
Oh I see, it's because this script is on multiple doors and each of them refer to the same text object
So each of them run on each frame and only the last one that runs gets applied in the end
I'm trying to think of the best way to handle it
okay thank you so much!!
Maybe not the best way but this would fix it. Make a new script on the interact icon object that has this:
private bool itemInRange = false;
public void ShowText()
{
itemInRange = true;
}
void LateUpdate()
{
gameObject.setActive(itemInRange);
itemInRange = false;
}
and then in the door script call ShowText when in range:
if(IsInsideInteractArea())
{
interactIcon.ShowText();
}
(change the type of interactIcon to the new script)
That way the door scripts don't cancel each other out
I'm trying to make a dash ability but character is won't dashing.
{
[SerializeField] private Rigidbody2D _rb;
[SerializeField] private InputActionReference _dash;
[SerializeField] private Movement _moveScript;
[SerializeField] private float _dashspeed;
[SerializeField] private float _dashduration;
[SerializeField] private float _dashcooldown;
[SerializeField] public bool _isDashing = false;
[SerializeField] private bool _canDash = true;
void OnEnable()
{
_dash.action.started += DashAb;
}
public void DashAb(InputAction.CallbackContext context) {
if (context.performed && _canDash) {
StartCoroutine(DashCoroutine());
}
}
private IEnumerator DashCoroutine() {
_canDash = false;
_isDashing = true;
float _dashDir = _moveScript._movedirection.x;
_rb.linearVelocity = new Vector2(_dashDir * _dashspeed, _rb.linearVelocityY);
yield return new WaitForSeconds(_dashduration);
_rb.linearVelocity = new Vector2(0f, _rb.linearVelocityY);
_isDashing = false;
yield return new WaitForSeconds(_dashcooldown);
_canDash = true;
}
}```
