#💻┃code-beginner
1 messages · Page 645 of 1
This script is on the bullet:
using System;
using Unity.VisualScripting;
using UnityEngine;
public class BasicBullet : MonoBehaviour
{
public float bulletSpeed = 0.3f;
void Start()
{
}
void FixedUpdate()
{
transform.position += transform.up * bulletSpeed;
}
void OnTriggerEnter2D(Collider2D collider){
Debug.Log("Hit!");
}
}
I'll take a look
Ah I see it's this step
The bullet has no rigidbody, should I make it kinematic? Would that make future development easier?
hello was following this https://www.youtube.com/watch?v=NsSk58un8E0, and it seems like I couldn't get the character to rotate with the camera and because the character rotate vector is used to determine the move vector, I couldn't get the character to move
The requested movement vector was fine, I tested it (but it wasn't flattened like I wanted to) and there seems to be some major error that I can't find
This one is a bit different than the last couple devlogs. I thought it would be fun to share a longer video where I actually make a thing. Might be super boring? Idk!
Links:
https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
https://youtu.be/7daTGyVZ60I
https://youtu.be/tYc1yUt0IeA
https://github.com/TheAllenChou...
if its a hitscan why not use a raycast?
It's not a bullet bullet it's a bullet hell bullet that moves slowly
ah i get it
But is translate moving just always a bad idea
i reckon kinematic since it's not a physics obj if its like bullethell
does anyone know why im not getting another box to change the walkspeed?
nvm i figured it out
Why a global variable though?
Thanks for letting me know, its an accident from the IDE
i accidentally added it i pressed smth
Oh ok
but i forgot what i had before
Don't even know what the global:: prefix even does tbh
Is it something similar as the global keyword in Python?
same
But now im getting this error
I dont need to add rigid body
it just adds gravity to the sprite (floor) and then it’ll just fall
If you don't need to add a Rigidbody, why is one of your scripts trying to access it? If you don't need it, then remove it . . .
@fading barn Don't crosspost.
I just want someone to reply with help
Your !ide is not configured. Do that first.
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
i accidentally added the code to the floor and the player instead of only the player
it is configured
i already did that
Try retracing your steps using the bot link above
Otherwise I suggest switching to Visual Studio or Rider which has an easier setup
what do i get for configuring the ide
the computer telling you what your fucking up and not this server
It will actually help autocompleting Unity related features and it will display warnings and errors in the IDE rather than it being shown during compilation
I doubt your C# side is working properly either if you don't have it configured
can someone please help me with this
UnityEngine.Graphics:Blit (UnityEngine.Texture,UnityEngine.RenderTexture,UnityEngine.Material,int)
RetroTVFX.CRTEffect:OnRenderImage (UnityEngine.RenderTexture,UnityEngine.RenderTexture) (at Assets/RetroTVFX-master/Runtime/Core/Scripts/CRTEffect.cs:276)
UnityEngine.GUIUtility:ProcessEvent (int,intptr,bool&)
its been driving me crazy for the past 3 hours and i cant fix it
Share your !code related to this and possible some additional details in the stacktrace if it exists
📃 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.
Because we can't help you on a single error
should i send it in a txt?
The bot message explains it pretty well
Large code block to a paste site, small code blocks inline using the format in the example
i wanna make an audio manager script to play all the audio in my game - how do I make sure this exists independently of whatever scene the game is in
so it doesn't cut out audio when switching levels or stuff
Singleton and DontDestroyOnLoad is what you need
Oh come did my unity get corrupted 💔
And i just started.
I had lots of motivation
and this happens
If this ain't proof life hates me then idk what is
do you know what the issue is?
such things are normal, sometimes unity just throws out internal errors, just restart or try to find out what is happening
Um, help. What happend.
top right corner reset the layout
This is a coding channel, not a UI channel
If this is not code related, prefer using #💻┃unity-talk
I have 10x the chance to get helped here but alright.
Not really
No
Your code points to the correct location
But your stacktrace doesn't explain the actual issue
its killing me i cant figure out why its doing this
i thought it could have been an asset i imported but i deleted every recent asset i added and turned off everything back to standard shaders to try solve the issue but nothing changes
i even tried to just straight up reinstall the shader but still no luck
god i really dont want to have to remake everything again from the start.
Okay but, you still haven't shared the issue
This has no error
Just the stacktrace to the faulthy code
I doubt it came with no error
Expand the console as a whole and screenshot the error message
Okay well I can't help with an error specific to the library you use unfortunately
It does give some suggestions. have you tried that?
yep ive tried to double buffer it and nothing changes
Same error?
yup.
is there anyway i can fix it by removing the whole shader?
like is it possible to save the rest of the game
is this not a #archived-shaders related problem?
is it not? it says theres an issue with my CRT overlay?
Why do my variables don't work in "If"
coudl you post your code please?
Well i'm like a utter beginner, (2 days.) but i followed a tutorial for a camera follow script, and i also have a object in game that destroys the object that the camera has to follow and creates a error, i want to solve this by making the camera check if the block exists before following it.
I don't know how though.
Placing "If" gives me 1000 errors.
so please post your code
I didn't add the IF since it caused 100 errors.
!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
you could wrap a simple if(target != null) around your code
May i ask why do i have to add the ! before =? Im curious.
!= means not equal to
I think this is what you mean?
yeah without the DontDestroyOnLoad it would look right
you need the DontDestroyOnLoad on a seperate part
why
how so? I thought that as long as you called that when your object is instantiated it won't get destroyed anymore
ey i managed to fix it turns out there was a script i just added that i forgot about that was scuffed i deleted it and now everything works
well try it out and see if it is what you are looking for. @ruby sparrow , not 100% sure if that is what you want
anyone know why my object keeps bouncing? the player object have rigidbody and so does the cube
it has gravity modifier aswell so in theory it should just stay on the plate but...
no it should be fine
check the physics material and the bounciness, this isnt a code question unless you coded it to do this
oh, where should I ask this type of question?
#⚛️┃physics maybe
usually in #⚛️┃physics or #💻┃unity-talk if you cant find any related channel. I did provide an answer though for where your issue probably is
quick question where is the physic material 😅
check the colliders, it could have a reference to a physics material asset. that would have the bounciness value
ok so followup question - audio can be played in 3D or just "in general", like background music. If I wanted an enemy to play sfx when they do things should I just attach an audio source as a component to it and get its own scripts or animations to play the audio?
you can use PlayOneShot
no need for a new Audio source for each effect
in general you create a List of AudioClips and play a audioclip with it index fomr the list with the use of PlayOneShot
Okay, so it works it dont give any errors if its destroyed, the problem is if my block is destroyed, it respawns, and the camera does not follow the clone. Is there any way i can fix that?
I think it has to do something with gameobjejct null, but if it appears again it means it isn't null any longer right?
Maybe it has to check for clones too, if yes, how do i do that?
and your PlayerMovement the OnTriggerEnter2d will not work you need to change the method
My cube does move though.
I added it for a delay
you need to call a coroutine after the ontrigger is detected
so you´d need to different methods, one for the ontrigger and one for the delay
Well most things seem to be working fine except for the camera does not folllow clone.
fine.
I don't get any errors from it so may i ask what exactly won't work
So how do i make the camera variables check if its a clone?
Ok i have a idea.
What if instead of a gmo it followed a object that has a specific tag?
But how do i do that..
GameObject.FindWithTag("YourTag")
Like that?
uh.. not like that
How do i do it?
On the top of your script, you can change public Transform target; to public Transform target = GameObject.FindWithTag("Player").transform
..maybe i don't have that much experience
welp.. the lack of my experience shows.. someone like me are more fitting to ask stupid question than answer someone's question so i'll leave it to someone more professional :)
I need to make clones follow the camera. Cam follow script
Can someone help with that?
(Omg no way these guys blocked "Can someone help" with automod.)
Use Cinemachine instead of programming this stuff yourself, then it'll be more flexible for any future changes or needs
Link please?
Thank you
Why cant my editor resolve the URP volume?
Using the correct import according to the documentation
There is a problem, there should be no pieces left inside my pieces parent object. Here is my code:
private GameObject[] pieces;
public GameObject slotcontroller;
public GameObject slotprefab;
private GameObject[] slots;
// Start is called before the first frame update
void Start()
{
pieces = new GameObject[piececontroller.transform.childCount];
slots = new GameObject[pieces.Length];
for (int i = 0; i < piececontroller.transform.childCount; i++)
{
pieces[i] = piececontroller.transform.GetChild(i).gameObject;
GameObject slot = Instantiate(slotprefab, slotcontroller.transform.position + new Vector3(0, i * 1.5f, 0), Quaternion.identity);
slot.transform.SetParent(slotcontroller.transform);
slots[i] = slot;
pieces[i].transform.SetParent(slots[i].transform);
pieces[i].transform.position = slots[i].transform.position;
SpriteRenderer pieceRenderer = pieces[i].GetComponent<SpriteRenderer>();
pieceRenderer.sortingOrder = 1;
pieces[i].transform.localScale = new Vector3(3.0518f, 3.0518f, 3.0518f);
}
}``` any problems here?
How do i delete components?
In code? With Destroy()
Right..wrong channel i meant ui.
Press the ... And click Remove component
Can you share the docs page?
Im trying to use cinemachine, and it says virtual camera is depcrated or whatever it means....all tutorials use it but it doesen't work for me.
Any fixes?
oh wait there's a cinemachine channel.
Although i probably would wait 10 hours to get help there.
post in the correct channel regardless.
I think its ridiculous to wait for something 10 hours when you can get help in 20x the less time.
I think it's ridiculous to critisize the free help your recieving
go learn it yourself
Debug with logs or step through the code with a debugger to see what's going on.
I think it's rediculous you think it's ok for you to ignore the rules of the server, to attempt to avoid an arbitrary made up 10 hour wait ¯_(ツ)_/¯
Im not criticizing the help im criticizing the rules but okay.
trygetcomponents dont work like that
the rules are designed for the help
we aren't cinemachine people in this channel
this is for people doing code things
you don't ask a plumber why your facebook isn't working
I'd recommend using the generic method. The one you use requires typeof.
Well i've been trying to make a camera follow script that works with clones till they told me to install cinemachine. Alright i'll use the cinemachine channel.
if (transform.parent.gameObject.TryGetComponent(out RectTransform rect)
parentPanel = rect;
i want to make my first 3d project what should i make cuz i cant even find a tut
Oh, right I was using it like the normal GetComponent, I am dumb
!learn:
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
thanks :>
hey y'all, does anyone know what the correct syntax to use is in this case? I'm trying to make some classes to streamline adding stat modifiers to my weapons
any help is greatly appreciated
if (getModifier is replaceSoundModifier soundModifier)
applySoundModifier(soundModifier);
Type and method names should be PascalCase btw. It's hard for others to work with your naming where everything is camelCase
thank you so much!
I have unfortunately realised that, sadly however, I began the project like 2 years ago when I was brand new to Unity and it's kinda just how I've named everything already 😭
Very easy to rename stuff with your IDE
I don't think I have a single comment in any of my code except maybe somewhere it says "THIS PIECE OF SHIT SOMEHOW WORKS AND IT ANNOYS ME" 💀
Luckily IDEs have great refactoring tools
This also feels like a code smell that can just be solved with regular polymorphism e.g. virtual or abstract methods.
really? I'll have to look into that
it could probably yea but it just seemed more intuitive to make classes like this so I can attatch them to scriptableobjects
idk I kinda just wing it all the time
That doesn't sound mutually exclusive to what I just said
I kinda mean like I'm already after writing a bunch of classes nd stuff so it's kinda late to rethink it now but I suppose I could do it now rather than having to refactor it all in a couple months
If you're using visual studio, it's ctrl+r+r when you select the name of something
What value does a [SerialiseField] reference to an Object have when it's not initialised in the editor? Is it just null?
How so?
(iirc, some details might be off)
unityengine runs on c++ but it has to interface with c#
so the objects presented in scripting are really wrappers of c++ stuff
when you put a class object, aka a reference type value, in a variable, the actual value of that variable is an unsigned integer, a reference to the object on the heap. null would be a reference of 0; that's true c# null, and very similar stories for other languages.
normally, in c# or any other managed language, you can't get invalid references; objects are only destroyed when they aren't referenced anymore.
but with unity's structure, c++ stuff can be destroyed, and that would mean the c# wrappers should be destroyed too; but you can't just magically change all variables with a reference of 0xAABBCCDD to 0, so you end up with an object that wraps null; but it should be transparent like how it normally behaves, so it compares equal to null, trying to do stuff with it can give errors, etc. that's unity's extra definition of null.
in practice the difference usually doesn't matter; that's why unity's version acts like null
I see, thanks.
protected override void PickUp()
{
GameObject player = GameObject.FindGameObjectWithTag("Player");
if (player)
{
playerCamera = player.GetComponentInChildren<Camera>();
if (playerCamera != null)
{
transform.SetParent(playerCamera.transform);
transform.localPosition = new Vector3(0.3f, -0.3f, 0.6f);
transform.localRotation = Quaternion.Euler(0, 0, 0);
isPickedUp = true;
}
}
}
Hi can I get some help?
How can I make the current game object point to the camera center
transform.LookAt(playerCamera.transform);
How do i make a script target only clones? Im trying to make it so a bullet dissapears after a timer, however it also destroys the "mother" bullet which is reponsible for the bullets existing in the first place..
Is there any way to do that?
script:
actually i realised this timer script is thrash.
how do i fix it.
Use a prefab for the bullet, don't use one that's in the scene then you won't have to worry about that
Sorry, dictionaries don't show up in the inspector? What if I have to inspect a dictionary? :(
What's the best practice for handling large amounts of dialogue, some of it semi-procedural?
I need to essentially be able to both have and handle a lot of story based dialogue, with the important features like
- trigger in order
- dont trigger more than once
- don't trigger some until story threshholds
along with procedural dialogue like
- scout unit having some variants of "I saw unit X at position Y"
- bunker calling for a resupply missing Z
- essentially misc tactical callouts generated based on current map information
How do i do that?
Dialogue is text based, but it's also handled through systems like encoders and telegraphs so the generic off-the-shelf systems wont work for my game, I need to be able to have finer control over presentation and specific triggers. I need to know mostly about storage and organization
why do you have a mother bullet to begin with lol
My guess is a cluster munition? All I can think of
you could use the serialized dictionary package, i guess? the common alternative is a list/array of structs
I have no idea i followed a tutorial which involved it placing the model into a variable called bulletprefab
there's no logic there that would imply that
do you know how to make and use prefabs
...Not really im on day 2.
yeah ok so it's telling you to use a prefab; why do you have a "mother bullet" in the scene then?
Wait you can make another scene?
you can, but that's not what we're telling you to do
Its basically the model
with the bullet script
You don't need to clone a bullet that exists in the world
drag the bullet into your assets panel, and you create a prefab that only exists there and does not need to exist in the world
a prefab exists as a file in your assets that can be cloned without already having to exist in the scene and have running scripts
Spent the last two hours troubleshooting to find a lowercase T causing issues for a script but only causing a null reference exception, so, y'know, if anyone else struggles today, don't forget, it's completely normal.
sounds like you don't have a configured ide...
or using strings which is just as bad...
yo
is there a media section or like something where i can fix a issue i have
wiht unity
this is a code channel
I find it extremly annoying how difficult it is to make delays to a script. At least for me.
Im trying to make a bullet delay, but its in a public Update so i cannot add a coroutine..
I think.
Hi, I have a problem with the cinemachine camera randomly going black past a point when on lazy follow
Is there any way i can add a delay to the fire function? (Please ignore the absolute horrendous code but its the only way its gonna work.)
Coroutine
How 💔
I know i need to add a ienumarator
but if i add it
i will need to rewrite a lot of stuff i think
you can't put Update on a inemurator
why would you put that as Update
These things are hieroglyphs to me (i'm on day 2)....
I just need a alternative for update that works on a Ienumrator
If it exists.
idk what you want me to tell you , there is nothing complex about this, its a method like any other that has special yield instructions..
you should consider going through the pathways on the unity !learn site instead of trying to brute force your way through understanding how the engine works
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
If you google any sort of Timer then you can use Time.deltaTime too..for a quick timer..
in two days of unity you already doing too much anyway.. you need to scale your scope down a bit..
I managed to do this with tutorials and some of my own stuff.
1: 2d top down movement (its a cube, copied with tutorials
2: If touch enemy cube gets destroyed and respawns. (Tutorial + some of my own stuff.)
3: Gun. (tutorial)
4: Shotgun (Edited the gun.)
5: Sprint (My stuff.)
6: Cinemamachine follows player (I still need to figure out how to make it follow the respawned player.)
7 Bullet disapears after time. (Discord help.)
The problem is.
If i just read and don't do stuff that interests me.
I'll lose ALL my motivation and get bored.
And i can't do anything against it.
Anyways i think i'll take a break now to avoid a burnout.
It's all about discipline, not motivation. You're only motivated (have the desire) to do something you're interested in (your goal). Building discipline will help maintain control when doing — in your case, learning — difficult tasks, especially, one's that you are not invested in or see as a means to achieve your goal . . .
I do want to learn it.
The problem is.
I get bored.
Im motivated and not motivated at the same time.
You're just starting out though, so give yourself time. Everything won't hit right away . . .
Thank you for advice.
Motivation gets you started (starting the car); discipline keeps you going (the fuel in the car). At some point, you have to stay consistent and drive yourself to continue when it gets difficult or you'll have a hard time getting anything done . . .
idk where else to put this, but lets say i have a package that has a dependency on the input system package. how do i define that? is that in the package.json or in the assemblies, or even both??
i see something about using a manifest but is that the same as the package.json?
ah ok so just the package.json and nothing else 
Here's a unity page about this problem
https://discussions.unity.com/t/unhandled-exception-system-invalidoperationexception-cant-find-file-pipe-unity-ilpp-8b1324c506b688d7b5c417750307dd42/1489170
It recommends you delete the Library folder in your Unity project and re-open the project. 
Can someone help me? I am (somewhat) following a movement tutorial, and I made my own dash system. whenever I dash into a slope / corner, my player will fly into the sky, depending on the angle.
https://youtu.be/FV8AezXf3vM
I'm trying to learn (because Unity is more careful and better done than Unreal Engine) and I'm trying to make it so that when you press "e" it puts a message in the console.. it doesn't work. What's the problem?
thanks, how do i access library folder
Go to Unity Hub and right click your project, press Show In Explorer
I think its Input.getKeyDown
no s for Input
thanks
You'll have to show the dash system for someone to tell what's wrong with it
The code is full of errors, and console messages appear in the Unity console, not VSCode. Configure VSCode with these instructions so that you see the error messages there: !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
You have a couple naming issues with the class you're trying to use. Try comparing to the documentation, the second example is exactly what you're trying to do.
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Input.GetKeyDown.html
Will it work anymore?
A couple things to notice
You're using 'Inputs.GetkeyDown' instead of 'Input.GetKeyDown'
You're using 'keycode.E' instead of 'KeyCode.E'
You're using 'Debug.log' instead of 'Debug.Log'
You're also missing a semicolon on the end of line 8
Now you just need to add the component to a gameobject in Unity and press play
You need to configure your IDE before you do anything else
My guess is you need to rename the file to Inputs so it matches your class name
otherwise you're wasting your own time and ours
Right now the file itself is named 'NewBehaviourScript' it should be renamed 'Inputs'
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
ow to use it ?
click the link for your ide provided in the bot embed
not sure if its a code issue or a physics issue, thats why I didn't at first
trying to see if I understand something correctly
if I have a script, CommsManager, that acts as the manager for the comms room
if I have a variable, like
public class CommsManager : Monobehavior
{
public static bool messageWaiting;
}
can I then access that variable from anywhere without needing to make specific reference, like having
public class GunneryRoomManager
{
if (CommsManager.messageWaiting == true)
{
signalLight.turnOn()
}
}
without having to assign the specific commsManager to the GunneryRoomManager in the script or inspector?
(in this example CommsManager has way more stuff going on in it than just having messageWaiting, but not relevant to this specific question)
yes you can do that since the variable is static
But it's not often a good idea to use static variables, especially not in this way
at the very least you should turn CommsManager into a singleton and make that variable not static
then access the normal messageWaiting variable on the single instance of the CommsManager
Why is it a bad idea to use static variables like this?
What would accessing the normal messageWaiting variable on the singleton look like? Would it require me to add the CommsManager to the GunneryRoomManager?
Well there's ttwo issues - one is the fact it's static.
The other issue is the fact it's a public variable.
The reason to avoid a static variable is because the variable ahs no ties to the lifecycle of the CommsManager instance at all. Let's say you were playing your game and you started waiting for a message. Then the player suddenly quits the game and goes back to the main menu. Then they load into the game again. The messageWaiting variable is still set to true, even though that's just stale data from the earlier game.
So you have this extra effort of having to make sure that static variable is in sync with things
if the variable is NOT static then its value is tied to an instance of CommsManager. So when the CommsManager gets destroyed it gets cleaned up automatically
bump because no reply
I think I understand, thank you
In my structure, any script with Manager in the name is only ever going to exist as one instance, would it be a good idea to convert them all to singletons?
Sounds like they already are singletons in that case. The step here is to add some things that reflect that fact. For example:
- A single static
Instancefield so other scripts can easily access them - Logic in Awake that enforces the fact that it's a singleton (e.g. destroying duplicates)
Singleton just means "a class of which there is only one instance at a time" basically
any amount of information on how your "own dash system" works would be required to give an answer
I could guess that you add velocity until you meet a specific horizontal speed, but you add velocity in the movement direction, so a diagonal vector adds way more vertical speed because it keeps going until max speed is met
but if you made it differently, none of that would apply
so a singleton isn't a thing, it's a design philosophy?
if I added the destroy on duplicate found code, that's all it would need, it sounds like?
basically yeah; the term is "design pattern"
here is the player movement script, the dashing code, and what it affects is kind of everywhere
there is a middle ground between "zero code" and "entire 300 line script" please cut out the part that handles dashing, the buggy element, and only share that
I actually prefer seeing the whole script, and I read it, I think it's really just a consequence of throwing your player object very quickly at an angled surface
I believe there is no buggy element, it is just as PraetorBlue says. the code will work normaly, except at slopes
i am just trying out how to fix that
yeah it looks a bit like you accellerate to mach 10, and trust ground friction to slow you back down
if you get any amount of air, you no longer have brakes
I would fix it by adding a delay, based on either time, speed, or distance traveled, and slow the player back down after that delay
how would that help not being sent in the air?
it wouldn't directly, but it's a start
you currently give the player an explosively massive velocity kick
on flat ground, this is fine, the ground will slow you back down
on a slope, you bounce upwards and suddenly nothing is digging in the brakes
instead of giving the player one massive kick, give them a constant burn over time
ok, thanks. Is it a physics issue then, or why am i going up in the first place?
excellent diagram lol
I'm a proffessional artist [lie]
To elaborate a little further
the faster you go, the more drag you feel
so if you give one massive kick hard enough to get a good dash speed going, for like a tenth of a second at the start of the dash you are SCHMOOVIN
if you bounce while schmoovin, you'll get redirected and your ground drag no longer applies
gravity is not subject to the accelerating returns that drag gets
why my player cant move right or left though im pretty sure i did everything correctly
transform.Rotate is rotating ur mesh/player
use transform.Translate
You didn't read their code, did you?
i thought i did 0.o
idk my previous tut used that and i thought that was good mb
cuz im trying to do a new simpel project with the things i learnt without tut
if they want their character to move left and right, but they're using transform.Rotate() wouldn't that just rotate the character and not actually move in ?
for the record im also a beginner when it comes to unity/scripting so like @slender nymph said maybe what i said is wrong
u are right the other tut was way diff
thanks :>
For the record do you want it to strafe or do you want it to rotate with those keys?
yeah, you meanie 😠 i fixed it >.<
like move left and right
lol
Because if you want it to strafe you need to combine your input into a single Vector3, normalize that, then use that in your first call to Translate
oh nice , good to know
it deleted everything besides the assets
Hint: they ARE using translate already, just not with all of the input. They don't need a SECOND call to it
Your comment says:
"Move the Player Left and Right"
Your code says:
"Rotate the player".
These are not the same
I see, so what I said wasn't inheritely wrong, it just wasn't the best solution?
yea i was wrong cuz i did a tut and it was different concept mb
Although ideally they shouldn't be using translate at all for this
WHATTTT !!!!!!!!!
my life is a lie
Player movement would ideally be using a character controller or rigidbody unless you want to do manual collision detection with physics queries
yeah, this makes alot of sense
nevermind i reopened the scene and everything works fine now
im making player movement and obstacles when they touch they die
is anyone like good with enemy control and barracks tower?
Okay then you want to use a character controller or rigidbody
oh lol
i dont know why but my soldiers are just standing there and not colliding with the enemy
i was making a collecitable and idk why it doesnt get destroyed though i did is trigger and rigidbody and all ?
and ik thats not a great way for a collecitable im trying new stuff
Start using debug.log and throwing it into your code blocks where you expect values aren't being set correctly
OnTriggerEnter params provide the method with what it is colliding with. Technically you're comparing against what has collided with the coin in this case
oh so if i want to destroy the coin what should i write
like to do the destroy to it
and not the player
Well, if you want the coin to check for the collisions, then in this case you're comparing if the player has collided with it
oh so i should do that script in the player script
Thanks :>
it's up to preference really. I'm not too sure what is optimal if there is
it doesnt work in that so probally the player will do the work
u are right i did a wrong move
it worked thanks :>
ok now its damaging the enemies but its not moving
change the map and use a assest
ok
gl
wait wdym by change the map
like replace the map?
yep
how am i gonna do that
no thats the the thing
u can use tilemaps as an example
ik
like they should go in front of the enemies and attack
but there just standing there and attacking
but it is just a simple thing that will make your game prettier
He is giving you seperate, unsolicited design advice
yep
tip, don't do that, he didn't ask for design advice and that's not what this channel is for
sorry
most people make the game work first, then make the game pretty
well can anyone help me?
why is the purple units not moving
but there damaging the enemies
what does the logic for enemy movement look like?
What normally triggers enemy movement, and is that happening?
put debug.log functions in your code handling movement, and see which ones aren't firing
well thats what i did for the barracks
because the enemies are working fine
i put debug logs everywhere in the barracks
they are working
but the unit isnt moving
i guess its prob something i did in the inspector
did i assign this properly?
okay, so you put debug logs in the barracks
now the enemies arent working, so you need some there too now
no the enemies are working fine its just the barracks are staying in one place while the system is changing its location and damaging enemies and stopping them
probably? I have no way to know that. you have put the transform of the barracks flag in there, if thats what you meant to do, you did it right
lets start from the beginning, and use less words like "its" and "them," they add confusion
What are you expecting to happen, and what is happening
be specific
since it's a prefab the BarracksFlag is also a prefab, which means it's not actually in the scene. You need to assign it once you spawn the unit
so im trying to make a barracks soldier go walk up in front of an enemy and attack it but for some reason the soldier unit isnt moving but it can still block enemies and damage them
you need to show your MovementScript.
EnemyMovement
I can't see it in your screenshot but I assume that script is attached to your Barracks Unit?
i need enemymovement script in my barracks unit?
you should place debug.log functions in enemy movement, to see if the reason is because the speed is zero, or the target is null, or any of a handful of reasons
trace the code path from enemy exists in the world to enemy actually moves, and place logs at each step, to see where the chain breaks
are baracks a unit or a building
are barracks supposed to move
whichever script is not working right, add debug.logs to that
how come when i parent a rigidbody to another it ends up bugging out and flying around
so im following a guide to make a grid for a 2d game
and i have a [SearalizeField] private Tile tilePrefab
and i made the tile prefab, but it wont let me assign the prefab, like theres the option to assign a tile but it just doesnt let me select the tile i made
Parenting not recommended for dynamic rigidbodies
usually joints are used for that
or actually is there a way to change the mass of a collider without a rigidbody since i cant parent it
can anyone tell me why im having this error?
your code's braces is a mess. Open and close your functions properly, and hit Ctrl+K, Ctrl+D to format your code so the scope of the braces are correctly indented—helping you see where you've probably gone wrong
the ontrigger isn't running when passed through
Are you saying you've fixed your errors?
Don't place the Unity Message (function) inside another Unity Message (function)
your on trigger is in update and your formatting is all wrong
private void Start()
{
private void ...//Incorrect
{
}
}``````cs
private void Start()
{
}
private void ...//Correct
{
}```
Thank you, I didn't notice that issue. It works now
Alright so i have attached a video of my issue. I have a lever which is meant to lower
the capsule down the hole but by doing so my lever is just disappearing when I click it instead of moving either
up or down. I have also attached a photo of the levers pivot point and the scripts for the capsule lowering
and the levers movement. what should be happening is the lever once pulled either up or down moves the capsule
up and down but at the moment I cannot solve how to fix it. any help would be greatly appreciated
https://paste.mod.gg/tufaovfeqkzn/0
https://paste.mod.gg/ufkgutvtmnka/0
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
Could be potentially the issue, but it looks like you're trying to store your currentAngle of the mouse input, but you're multiplying it twice, giving you a completely different value than where your mouse position actually is.
how would i fix that?
Most likely it's actually still in the scene (not deleted) its just been flipped or rotated into the ground. Try playing with your values at small increments and see if it still disappears
where do i change the values?
Lower your rotationSpeed to a small value and see if that helps
In general, you start investigating such issues by looking for the object in the scene hierarchy/view during play mode and investigating it.
What crazy mentioned is probably correct, but you should always have a full grasp of what's happening.
"public float rotationSpeed = 100f; // how fast lever rotates from mouse movement" this is what im changing right?
what was the original problem you are trying to solve?
the rigidbody is the object with mass, collider just defines the shape
changing it in the initializer only works once the script is added / reset . Otherwise you should change it in the inspector
i set it from 100 to 10 but its still the same it just gets thrown into the floor
^^ Change it in the inspector and start at something like 1f. In certain cases a 1-1 ratio for mouse movement is "raw" movement, multiplying it by 10 will give you 10x faster than your mouse is actually moving.
If you want it to match mouse position, you'll need to do some raycasting into the scene.
i cant tell if its changing anything cause when i click it it basically disapears into the floor almost instantly
And then some extra math
Debug your code. Use logs or attach a debugger and step through the code.
i just checked in scene and when i click it it goes into the ground then falls
Why does it fall? Does it have a dynamic rb?
im not sure what this means it has a box collider maybe thats the issue?
No. A collider is not enough for physics simulation. It likely had a non kinematic rigidbody. Or it's parent has.
Looks like you've found your issue, the lever is falling, due to the RB attached to it. You should try freezing its position or setting it to non kine like Dlich said
If you don't understand how unity physics work, I'd suggest going over the beginner pathways on unity !learn:
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
no reason a lever should have a rb with gravity..
so i leave kinematic off?
no reason to really have a rigidbody on it at all
this is all so confusing ahh
everything is confusing when its new
so far its been pretty easy to grasp this issue its just mind numbing to me
the pathways is probably the best way, you're rushing too much into it
That just means that you barely scratched the surface
well its working its just your pivot looks weird
should probably show that in scene view with gizmos + hierarchy
You've got your lever almost figured out, keep in mind how Vector3 & Quaternion's work (x, y, z)
when i move it around it shows that the X pos is moving in transform thats the right pivot angle it should be moving but its not doing so
local and global are very different axes
its gotta be something with this right? if (isDragging)
{
float mouseY = Input.GetAxis("Mouse Y");
currentAngle -= mouseY * rotationSpeed * Time.deltaTime;
currentAngle = Mathf.Clamp(currentAngle, -maxAngle, maxAngle);
transform.localRotation = Quaternion.Euler(currentAngle, 0f, 0f);
should i change it to x...?
i have a boat i am trying to have the player move with, it moves with a rigidbody that has forces applied to it. when the player goes on it i want it to basically act like a moving platform but i am using fishnet networking to network the player which is similar to netcode for game objects where you have to parent objects only to the root object of a hierarchy, (not the scene but the highest object in the tree if ykwim) im setting it up in singleplayer first and then porting it to my multiplayer scene so thats not part of the equation as much. i can use any player controller, rigidbody or character controller based but when i use a character controller it affects the boat and pushes it around so i was using a rigidbody with a really high mass for the boat and a rigidbody with a low mass for the player but obviously parenting doesnt work because they are both rigidbodies, i have tried putting an exclude layer on the boat rigidbody and creating separate colliders that follow points on the boat with a parent constraint and a script that moves the player with an offset but it was really jittery
no, this is just about multiplying mouse input by delta time (as the title and link suggest) and why that is wrong
hmm with character controller you could make the boat itself kinematic btw so it doesn't get affected by the player, and its a bit easier to move with or possibly parent it..
For rigidbodies I'd probably still make the boat kinematic, and you could move the boat with playervel + rb dir in code
im new to kinematic rigidbodies so i dont really know much about them, i am using add force to move the boat, is there some equivalent for kinematic rigidbodies or do i have to do out the buoyancy calculation and use move position
I got an event listener set up in the inspector, how would I change the parameter there at runtime using a script?
if you don't want hard coded values, then you would instead pass the desired value when you invoke the event and subscribe using the Dynamic option instead of the Static option
https://unity.huh.how/unity-events/dynamic-values
what dynamic option
well Button does not have that because its onClick event does not pass any data
you'll need to use the workaround if you want to pass dynamic values https://unity.huh.how/unity-events/method-requirements-workaround
or if that isn't actually on a Button, you would declare the UnityEvent<T> with the type of parameter you want rather than just using UnityEvent (without a generic type parameter)
Is there a way to reference a bool in a collided object using Collider2D.gameObject.GetComponent or something?
I'm making a remake of frogger as a learning project and want to check for that bool on collision to see if the collision should kill the frog or not. Is the only way to create a reference for every separate obstacle that has the bool in their script?
you can use GetComponent to get the actual component that your public bool actually lives on then access it from the returned object
is there a better way to address things in the UI Toolkit by their labels?
slots = new GameObject[pieces.Length];
for (int i = 0; i < Mathf.Min(pieces.Length); i++):
pieces[i] = piececontroller.transform.GetChild(i).gameObject;
GameObject slot = Instantiate(slotprefab, slotcontroller.transform.position + new Vector3(0, i * 1.5f, 0), Quaternion.identity);
slot.transform.SetParent(slotcontroller.transform);
slots[i] = slot;
pieces[i].transform.SetParent(slots[i].transform);
How to make i < ... stay constant. (By constant, I mean if the length of the original piececontroller child component equals 4, variable I run until 4 and not 2.)
Mathf.Min(pieces.Length)
this doesn't make sense, obviously pieces.Length is the minimum value there . . .
probably. I only used UI Toolkit for Editor tools and used C# so everything was done with fields n by just creating Element objects.
might be better off asking in #🧰┃ui-toolkit though
Are there any beginner tips for how to build a save system for a game, such as should I use a tool that saves the scene setup and then a separate tool that saves the game object fields?
I am using Unity Starter Assets FPS Controller and here I am all along just pressing the FWD Button yet as you can see the Player GameObject keeps going back after bumping into the Wall ....this is happening all the time after bumping into any obstacles it keeps going back
are you changing the position of your object or moving with physics?
I am using the Starter Asset and in the code I am not seeing any RigidBody Tweaking also there is no Unity Rigidbody component on the Object only an addition code script that handles object push logic but I have turned it off...
yeah so you have to use physics based movement instead
i tried that but I ran into a weird problem with my GameObject. The movement feels sticky around walls and anytime I jump to some obtacles it gets stuck to the wall for a moment and then slides back down...
So the movement is purely unity's FPS controller? Did you add any other components to the player?
So I had been trying a FPS Movement with RigidBody and it was working well but it kept getting stuck on walls and I did not know what was happening
P.S.
this is why I thought of using the Asset Store's Unity Start Pack FPS Movement Code (as it also adds Controller support and stuff)
FYI This was the OG Movement Code with RigidBody
you can make use of physics materials
I have gone back to this RigidBody Movement
yeah so assign some physics materials to your walls/your player and play around with the settings
Most importantly use low friction on the physics material
And friction combine = minimum
as in? how do I do that?
do you mean assign Rigidbody?
Create a physics material, assign it to the collider and adjust it
I am very new to this ... do you mean adding a Rigidbody component by physics material? or is there something else called Physics Material?
You are expected to
this stuff. All the info is online
Oh Sorry Thanks
Googling "unity physics material" will take you to the doc
why does my invoke not refrence the function
its not refrencing it but it has the same name
is it the capitalization
cuz ive been swapping that around too and nothing
what do you mean with not refrence the function
can you see the debug log end of movefaster powerup?
nope
it just doesnt play
my reset move speed doesnt get called at all
ok then can you see the debug log hit movefaster powerup
yea
ok just use a Coroutne instead the Invoke, it is recommended anyways.
StartCoroutine(Reset(2.0f)); //call
IEnumerator Reset(float waitTime)
{
//doSomething
yield return new WaitForSeconds(waitTime);
//doSometing
}
so you could get rid of the deactivate method too with this. you cna simply call your code after the WaitForSeconds
would i still be able to adjust it in the editor
you can still work with the inspector if your fields are serialized
all the variables you had before, you can use them too
rebirthCount isnt going up for some reason but been.numOfBeens is getting set to 0
they are both in the same if statement, it makes no sense that one is set and the other not
use a Debug.Log inside the if statement
been.numofbeens is not higher or equal to calcprice by default so i assume your statement is never met
no i made it higher manually
ah i see now
any idea why this is happening?
alright
A tool for sharing your source code with the world!
couldnt find those two so i just used this
Actually debug the value that you think is not going up.
Not just a meaningless text message.
looks like it is going up but getting reset back somehow
Ok, then add logs in all the places where you modify it and see where it is happening
alright thanks
If you have several of these scripts in the scene, it would also help to log the object name or ID or something to make sure you're looking at the correct data.
Ok, this is from UI but pretty sure I need code for this. I want that sprite to be a width relative to its parent and the height always be the same as the width. How can I do that?
you don't need code for this.
just tick the "maintain aspect ratio" on the image
and then either stretch or layout groups
refer to #📲┃ui-ux if you need further help
No, that does cap it to the min of them. I want the image to overflow the container on height if it needs to
make the container bigger then, or like i mentioned before, check out layout groups
https://www.youtube.com/watch?v=NsSk58un8E0 It's like my third time asking but can someone tell me why does my camera rotation doesn't cause the player to rotate with it? Additionally, why can't my character move when I pass the requested movement into groundedMovement? (debug line doesn't exist => vector is 0) (timestamp @ 6:45)
This one is a bit different than the last couple devlogs. I thought it would be fun to share a longer video where I actually make a thing. Might be super boring? Idk!
Links:
https://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
https://youtu.be/7daTGyVZ60I
https://youtu.be/tYc1yUt0IeA
https://github.com/TheAllenChou...
my requested movement exists (as ive debugged it and tested it), which indicates to me that a movement vector should exist as non of the variables i passed should be 0
Rider or VS or VSCode?
all 3 work fine
if you have experience with one of them use that
So nowadays you'd say vscode + .NET + unity ext is a solid equivalent of VS?
!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.
Well I use both VSCode & Jetbrains tools
definitely not equivalent, but it'll work fine.
Oh is this like a pastebin
VS is purpose-built for this language, (and similar languages) so it has more QOL tools built-in, but they aren't strictly necessary, and if you search around you could probably find some extra extensions for vscode (probably not all vs features though)
Write code in at least a code block
public class myCodeBlock {
}
yes
mb
Well I'm tempted to learn how to use VS, but it feels bulky at the same time
give me a bit
I'll try this out, thanks for the answer 🙏
well if you're already familiar with the other 2 you can just use one of those
vscode is better than vs imo
rider is also purpose built for c#
it'll have differences of course but it'll be similarly capable in itself
vs is annoying to deal with sometimes
Does anyone know how to program a really good race car? I tried following multiple tutorials, but the physics are always wonky in some form or another.
if you ever hear an unconditional "x is better y" in this kind of discussion, it's either an personal preference or theyre trying to sell you something
start with what you have and ask about how to fix the issues
also if your results aren't consistent with what's shown then go back and make sure you've followed all the steps given
do I just paste the link for the pastebin here for my question
A tool for sharing your source code with the world!
Well one car I tried was a simple truck model that moves forward and turns left and right, but the issue with that one is when it tilts or goes off an edge. When that happens it suddenly gets the ability to defy gravity and can be made to drive in the air in random chaotic circles.
The other one uses wheel colliders, and that’s a bit better, but it’s still way too slippery and has a tendency to bounce around and flip over. I can’t quite figure out how to get the settings just right.
Just FYI, I am trying the latter one on uneven terrain sometimes.
I can only make the container bigger in pixels or relative to height, but I want it to just copy the width in pixels
uhhh are you sure that one is physics based
What else would it be?
moving the transform directly
Yeah, that’s what it was.
you can use autolayout https://docs.unity3d.com/Packages/com.unity.ugui@1.0/manual/UIAutoLayout.html
go to #📲┃ui-ux for further help
yeah well then that's why lol
MR question: I dont want to deal with having to upload it to quest every time, but i need to test out room scan-related features? is there any way to have a "placeholder" room scan?
(zova just fyi im on mobile so i can't help you currently, reading code on mobile is really painful lol)
nah bro take your time
apperciate it
can somebody help explain why my tree ends up on its side?
How does the prefab look in the editor when you set its rotation to (0,0,0)?
I have a variable that is supposed to be a gameobject, but when i put any gameobject it says type mismatch, any solution?
Are you trying to reference a scene object in an asset?
Because that's not possible, and it causes the type mismatch
Is there a way i can put the variable without changing every single individual
to it
manually
Every single individual what?
If you change the prefab then its instances in the scene will be updated
Well i need that variable to be put in prefab somehow...
I can't start
the game without it
(It gives a error)
Well but i cant put the position in the prefab.
Therefore said individuals cannto be updated automatically
Wait im just as confused as you.
You mean a transform?
Maybe take a step back and explain what you are actually trying to do
Okay so i want a triangle (which is a prefab) to follow a player. I copy and pasted something from the internet that looks like this
Yes im an idiot.
Okay so you need the instantiated object to have a reference to the player
When you instantiate it, assign the player reference to the instantiated component
..How do i do that?
You should have something like cs public NewMonoBehaviour prefab;
Then you do Instantiate which returns the newly instantiated component.
So something like cs NewMonoBehaviour instance = Instantiate(prefab, ...);
Now you have a reference to the component of the instantiated object, and you need to assign the player reference to it.
You can have a Game manager/singleton script or something where you keep the reference to the player.
I don't have time to explain it better. Someone else can take it from here, and/or you can look for tutorials online
If you don't have any idea what any of that means, check out the beginner unity and C# courses in the pins
Prefab Dependency Injection
so it is actually easy, in the script where you instantiate your prefab you can directly assign the needed fields from the very same script
Instantiate() + manual Init() or something is a good design 👍
public GameObject prefab; // your prefab
public Transform target; // the target you want to assign to your prefab after instantiating
GameObject go = Instantiate(prefab, position, rotation)
go.target = target;
something like this should be fine.
on 99% of my stuff It has a Init() function which i pass critical deps as args (or a InitDependencies()) if init can refresh its state.
Sorry to jump in the discussion, can anyone help me out figuring which architecture pattern is best fit for the simple mobile games in unity ?
sorry but what is architecture pattern?
All is fine but there is one problem..im on day 3 and i just dragged the prefab from assets and placed it into the world, i dont have a script instantiating the things
i'll use this for later tho
You asked in a code channel so we all assumed you mean code
In any case you need to use code for this
I mean you can drag the reference to the manually placed prefabs in the scene
Without code
Like MVC or Dependency Injection , Higher order Function, DDD. I have some experience working in more business coding setup. I was wondering is there a standards in game dev
Something like this but I guess with example https://genki-sano.medium.com/simplified-clean-architecture-design-pattern-for-unity-967931583c47
Like how do people structure projects in production, so that multiple people can work on it following a pattern
and what does that have to do with code beginner?
Sorry if I picked the wrong channel, is there any other channel that can help me ?
I eventually just decided on instead of a gameobject made them follow a object with a tag
which solved the problem
of having to put the transform details into the prefab
the question was related to what Zaharaya posted
sorry for late response, in the editor it already is 0,0,0
Maybe that's how the mesh is rotated then. Or the renderer is on a child and the child is rotated
not 100% sure, but could it be because you are parenting it in the instantiate method?
what happens when you dont use a parent in the instantiate
sorry?
can you remove the transform in the Instantiate line
i did now and it does the exact same thing
If it's sideways at 0,0,0 then you'll need to either specify the rotation you want it to spawn at or fix the prefab so it's facing the way you want at 0,0,0
You'll use MVC and Dependency Injection along with other types of architecture. It really depends on the system you are building. They will all work together to combine your different game systems/mechanics
Some people try to stick to one main architecture that is a base for most of their systems, but you will utilize others. To answer, there is no one method for any project. You should prefer (and learn, if not yet) composition over inheritance. Unity uses a component-based approach; building your scripts and GameObjects using that structure will help set you up . . .
Open the prefab and make an empty parent object at 0,0,0, then make the mesh a child of it and rotated how you want it
Thank you for the answer, its just that I cant find a good example of a game that are following a design patterns. They all describe the pattern but I am missing the implementation part. And I feel there should be something that can be utilised in a team environment where everyone knows how the project should be structured. I would assume in game companies they would use a specific architecture for a specific game and as you say for different mechanic and game system different patterns would be used. But do you know a good example of github for a game that uses a good structure and follows a specific pattern ? Or what is considered an industry standard in unity for a small project
Thanks for the links, I was looking through the unity tutorial and have downloaded the demo project, it's very nice demonstration and covers a lot of interesting concepts and yes this is exactly what I am looking for. But the code itself is not showing the implementation at a scale. I get the idea for the component but I want to see a whole project that is written following a pattern.
you download the ebook as well ? has more examples I think
there is no hard rule on these things so you would use the same patterns you're accustomed to, just have to work around the unity quirks of things
all examples in ebook show those quirks in a unity setting
I see, yes it seems that way, I see the code example in the book, but I am not sure how to structure a whole game around this one pattern. But lets say I want to build a subway surfer game. Which design pattern would be the most optimal for this type of game. I would use MVC to build the UI elements and than use a different pattern, like a singelton to build the Player and the Enemy ? This is what confusing me. Like if there is a good solution to how you can structure your project so that it's not a mess when the project growth. And when I work in a team, how can I split the task so that each team member can contribute to the project even by writing one simple script that would have it's place in a bigger game based on the pattern.
Again, there is no real hard rule .
Not all patterns are hard coded requirements, they are just there to make things cleaner for yourself, more like suggestions / proven methods that provide specific results.
Its not really realistic to say" I am making [Insert Game Type/Genre] " and just say use this specific patterns.. The important part is you knowing what those patterns do exactly and why they are important with code, they are for your knowledge .
If you want your project to thrive, imo is much more important to have an overall outline, work more important things like working out Top down approach to your project.
Seems you are in the stage where you are creeping into paralysis by analysis, don't overthink it. Its good to set a baseline for clean code but don't let too much of rigidity block progress, or in most cases creativity.
If you want specific people to work on specific parts, have your overall plan then break down into smaller problems to solve, and then each person/team can work on that specific problem
I think you have a valid point, thank you, I do feel like I need to have a bit more experience with unity engine to figure out how I want to structure my projects. But thanks, I think I was thinking that the should be one pattern per game
To put it simply, you use the pattern that best fits the mechanic or system you are trying to make. An entire game will consist of multiple patterns. There is no rule where an entire game follow one or even two patterns. You will utilize many across your project . . .
Yea! its good to ask questions ofc. Good idea get in there before doing your "big project" and do some test projects, play around with different ways to solve certain problems related to your projects (ofc some problems you have to take as they come)
The hard part is figuring out which pattern fits best; the only way to tell is by building (coding) it and testing. If it doesn't feel modular or hard to edit, then a different pattern may be better . . .
Yes, I think you made this point in the beginning, which now that I have thought about it makes, sense thank you for, the answer as well )
Thank you @rich adder nav and @cosmic dagger for the help, I feel that I got what I was missing
Was eating dinner, will try now thanks!
sorry i dont know if this is the right place to be saying this
but how can i open 2 scenes at once in inspector?
you mean the hierarchy ?
just drag n drop in the new scene into it (hierarchy)
found it
oh i mean how can i view them side by side
so i can see both "maps" at once
Hi, can I ask here a simple question? I have setup a panel that can be open and closed, but after it is closed there is afterimage, line on screen (the panel now is closed) any idea why?
like each scene into a separate scene view?
yea
that I never tried, not even sure tbh lol
ahh ok thanks anyway 😅
don't think its even possible but maybe google might now
yea asking now haha
can someone help me im making a tamagochi inspired game and i wanted to test is my code that assigns and deals with stat's work but i cant attack text to it when i click in inspector to atach it it says scene : none
very unlikely oyu have any Text components in the scene
Text is the legacy UI component that nobody uses anymore
You probably have TMP_Text in the scene
except for the obvious is there anything inherently bad about using the legacy UI stuff because if theres less my mind can wrap around it easier...
Text will generally be blurrier/less sharp
there's really no good reason at all to use the legacy stuff
okay good to know. sometimes a lot of things can get confusing but ill watch a tip video while half asleep. usually cements the idea into my unconscious 
TMP is just a total upgrade, so really no good reason not to use it
the text component is called legacy now since the only reason to use it is a legacy project
Hello i am looking for a way to move my player. i usually use transform.translate but he sometime passe through my gameobjects. i found someone who use rigidbody.addForce but i dont understand very well how it work (how to block the speed, dont block the speed when i press my left and then my right key, etc ) someone know an other way to move my player ?
thats tricky i was struggling with the same thing. rigidbody physics can feel a lot more complicated than they are but they're an easier fix than you think to this specifically
The most analagous way coming from Translate would be to simply set your Rigidbody's velocity directly.
yeah so its not super slidy and all
If you do 3d there is also Character Controller where you have more control and not have to deal with outside forces, getting stuck as easy
depending on your usecase i would look into something like the Kinematic Character Controller asset
like ```if(rb.velocity > 5)
{
rb.velocity = 5
}
ya KCC is free now very good asset
No?
is the problem that your player is super slidy when doing rb.addforce?
its less work then doing it all from scratch and has less problems then the character controller
yes
no, just like:
void Update() {
rb.velocity = inputVector * speed;
}```
okay so instead of doing rb.addfrce
You can also . Vector3.ClampMagnitude(velocity, max)
yeah this
Ohhhh ok i see
instead of adding a force it kinda just sets the speed meaning that when your input vector is 0 the speed also becomes 0
which means no sliding 
but yeah if you want input you would need to use that in your calculation instead of a hardcoded number
okay its not like i need to share my work anywhere i joined just to have some connection to other people who are doing the same thing that im doing but
is there a place in this server for sharing work no matter how crappy 
oh yippee
can you assign a gameobject from a scene into a prefab?
Are you asking if you can create a prefab from a gameobject or are you asking if you can assign a prefab(gameobject) to a SerializedField in the inspector?
im asking can you bring a gameobject in the hierarchy into a prefab
like if u have a serializefield
yes you can use scene objects as prefabs
can reference and instantiate them just like if it was a asset
Hello I have a specific question about a certain unity developed mobile video game but I don't know what channel is the correct one to ask in, but I would really appreciate any help.
Yes, you can drag the prefab gameobject from your assets folder into the scene/hierarchy or use Instantiate() to have it created a run time (you will need a reference to the prefab object)
Hi all, I have a super general question regarding some of the function types, modifiers, and the general language of C#, specifically in the context of Unity.
There's a ton of language used in the Unity Junior Programmer pathways that is never explained, maybe I'm thinking too deeply about it, but it feels impossible to memorize all of the language.
For example.
public float speed = 40.0f;
void Update() {
transform.Translate(Vector3.forward * Time.deltaTime * speed);
}
The instructor doesn't explain really well at all where the words are coming from, their definitions, and it feels like I'm having to form my own relationships in my head between the words. From my current understanding:
Transform = change
Translate = Translation, being the position among the xyz coordinates.
Vector3 = a vector created by using the 3 coordinates (xyz)
.forward = +z
Time.deltaTime = I know that this line is responsible for making movement frame independent, but I don't know why, and it's never explained.
speed = just the speed variable that's set as a public float.
This example is really simple, but I can see it slowly becoming a problem as I progress with situations like the time.deltatime. Should I give up on understanding the root of all of the language and just accept it for its purpose at face value? Or should I go down a rabbit hole to understand each individual piece of language?
Sorry for the wall of text, I didn't know how else to convey my issue and I'm still brand new to this.
most of this can be looked up in the documentation like the docs for Vector3 will show what forward is, same thing for the Docs for the Time type
The best course of action to take for learning what each of these do is to reference to Unity Documentation - https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Transform.Translate.html - Most of them will give a brief blurb about what they do.
Holy mother of pearl dude - follow up question. Is there a reality where it's possible to know all of these?
what do you mean by know all of these
you find things you do not understand you research them and find out, and next time you see it you already know
I guess my question is - is there a great level of redundancy? How much roughly is even used?
not sure you mean by used
Each tool is used for different scenarios. A lot of the ones you referenced are the basic "tools". Translate, Vector3, Update. Will be used in 80- 90% of your scripting.
like i been programming for 20 years and still often consult documentation even for stuff i have used for a very long time
Gotcha, that makes sense so far as it seems its becoming a common trend in the modules on Pathway.
Oh really? Okay so how do you deal with NOT knowing that you don't know? Like for example if I didn't know about transform.Translate, how would one realize that they're missing something?
you get a feel for things eventually
no
thats not what i meant
i meant by like if u have a transform in your script
and its on a prefab
can you assign something from the scene hierarchy into the prefab script transform?
not unless its a instance
prefabs can not refrence scene stuff
so i have to make it an instance?
in order to put a scene gameobject into a prefab script transofmr?
well if its a instance its no longer a prefab
but more or less a prefab IE something that exists as a asset can not refernece scene stuff
Google is your best friend in this case. A quick google search of "Unity move gameobject" or something similar, check a couple threads or code for their methods and then cross reference the Unity Docs for which method best fits your need 🙂
That makes sense, so essentially it's trial, error, google over and over and over again until you're pretty good at this. lmao
You'll learn as you go kind of deal
its breaking problems down into smaller problems then researching what is required to solve each of those
I'm gonna keep at it then haha, I was mistakenly hopeful that there was some sort of magical linear progression by doing modules, but that's just copium I think.
Searching through code with google, you'll eventually stumble onto some code you've never seen before and later in your project, hopefully you'll remember reading something about a method to do what you want and then be able to jump straight to the Unity Docs to find what you want. A little studying beforehand will save you excess studying later
I think using AI to simply right click a general location and asking “explain how this works” after copying/making the ai make something is my best way to learn
Intellisense for Microsoft visual studio is great and all but the copilot ai has helped me understand every word and how they can be used because it takes right from the documentation
But then you need to strike a balance between testing yourself and just letting autocomplete autocomplete because you know you know how it works
abit late to the party but just wanted to chime in and also say going off that it can totally be valid to go down a route that probably isn't what your looking for in order to get first hand experience on why that idea might be flawed
a lot of the time the internet will be like "dont do x, do y" and it can be hard to fully understand that kind of advice until you understand exactly why those kinds of conclusions have been made
(and sometimes it's not always strictly applicable advice!)
how much c# should i learn before i jump into unity, ive spent the past couple days writing code and understanding c# to an extent but dont know when i should start any tips ? kinda feel stuck in a loop
you should understand the absolute basics of the language, including how objects work, referencing other objects, and (ideally) some of the more intermediate topics like events
is there a road map u suggest
no
https://learn.microsoft.com/en-us/training/browse/?products=dotnet
(its not really ordered well but most beginner stuff is there)
also keep in mind that what i suggested is far from an exhaustive list, because a list of "how much c#" does not actually exist
guys i have a question
can you drag a gameobject in a scene and put it into a prefabs script?
no, assets like prefabs cannot reference scene objects. you need to pass the reference at runtime to the instantiated objectJ
https://unity.huh.how/references/prefabs-referencing-components
does it work in a game if you like assign a prefab to the script the object is going to move on and then keep on duplicating the prefab in the scene?
what?
i want to have like when i place down this item the gameobject goes to the nearest assigned prefab available so does it work if you assign the prefab into the script?
what does "the nearest assigned prefab available" mean? because prefabs don't exist in the scene therefore they are not near anything
nvm
I started with Unity Pathways, and honestly, it's not going terribly. I'm confused as fuck sometimes, but at least things are becoming more and more familiar slowly.
its just a lot to learn upfront if you are coming to unity without previous programming or experience making games
Gotta start somewhere xd and it's WAY better imho to start with something where I can visually see the effect that my code has (or doesn't have xd) on the scene.
like my experience in unity would pretty easy but i came in already knowing how to make games and program
Learning code without some form of motivating factor, like something as simple as making a 2d mouse or 3d vacuum move in a scene to give me that boost of dopamine has always been such a drag to me. I've tried learning to code in the past with python and JS, and both were nightmares because there wasn't any substance to the exercises aside from a green checkmark :P
thats pretty normal, i first learned a pretty long time ago, and did so pretty much out of spite, was doing environment art and the tools in maya were pissing me off
thats pretty funny actually
Im following a tutorial to make a grid for my game, but i am getting these errors
Ive followed the tutorial perfectly except where mine is a GameObject theres is Tile. but i couldnt get Tile working and swapped it for GameObject
if youre following a tutorial then you should follow it way more closely. you just have basic c# errors, and these errors are quite clear as to why they dont work
also !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.
you cant just swap out a type and expect it to function the exact same with all the same methods
well i tried replacing the GameObject for Tile and it still broke the same way (and still had my previous problem)
oh i found out the ColorPrimaries problem
it was whatever c# helper thing i was told to download being annoying and just autofilling without me realizing
then follow the tutorial more closely, either the tutorial has a compile error (which id doubt) or you didnt copy it closely
Tile doesnt have an init method either
yeah i followed the video very closely
took a break from c# recently, semi-forgot how to program on C# any advice on how to go back into it?
or is it just dont think and go-in
guys i have a very very basic question
if you created a variable in a function, can you use that variable outside of the function?
depends on your skill level of it. if you were decent at it before then picking it up again by just going into unity should be fine
cheers
no, this would be local to that function only
!vscode
thanks
I have these two scripts, I can't seem to get it so when the weapon collides with the enemy it damages them. Could someone please help? https://paste.mod.gg/geenhwactswn/0 https://paste.mod.gg/ataaephpwrrp/0 The EnemyAI script has the damage part near the bottom of the script
A tool for sharing your source code with the world!
A tool for sharing your source code with the world!
It's important to note that while using OnCollisionX() "Notes: Collision events are only sent if one of the colliders also has a non-kinematic rigidbody attached." So be sure your weapon or enemy has a collider and the other has a rigidbody (set to isKinematic if everything is script driven).
If you're still having trouble, try adding some Debug.Log() lines before checking for the object's tag
Wait, so do I set the RigidBody to isKinematic or not?
Not if you want OnCollisionEnter to run
okay
Hi all, and good day! I am a beginning developer and musk ask for your help.
Attached a recording of the issue, and please do let me know if I need to provide any additional info.
The problem
I have created a player object that perfectly detects collisions below, but behaves very oddly around vertical collisions: it just gains height and/or goes through. The walls' collisions are fine and are not set to trigger, so the player shouldn't be going through them.
I suspect that the RigidBody component that I am using for this player is the reason why this happens.
The issue is, I cannot remove the RigidBody component, as it is crucial for one of the core mechanics.
Additional Info
- Here's the list of the components that the game object has:
_ Capsule (Mesh Filter)
_ Mesh Renderer [DISABLED]
_ Capsule Collider
_ RigidBody
_ PlayerController (Script)
_CameraController (Script)
_AudioSource
I have tried the following so far:
- Learned that "Character Controller" component can be useful, but when I add that component, the object gains height indefinitely on the Y axis upon detecting ANY input.
- When I remove the "Capsule Collider" component and leave only the "Character Controller", the object falls through the ground.
- The results were identical when I tried a box collider instead of capsule.
Without seeing your code it's hard to say what's happening
Coming right up
you definitely don't want to just randomly add a CharacterController
It would also be good to see what the settings are in the inspector for the components on the player and the walls
{
public float moveSpeed = 4.0f;
public void Navigation(float verticalSpeed, float horizontalSpeed)
{
transform.Translate(Vector3.forward * Time.deltaTime * moveSpeed * verticalSpeed);
transform.Translate(Vector3.right * Time.deltaTime * moveSpeed * horizontalSpeed);
}
void Update()
{
if ((Input.GetAxis("Vertical") != 0) || (Input.GetAxis("Horizontal") != 0))
{
Navigation(Input.GetAxis("Vertical"), Input.GetAxis("Horizontal"));
}
}
}```
you're using transform.Translate to move your character
this completely ignores and bypasses the physics engine
if you want your character to respect the physics simulation you will need to start moving it via the Rigidbody
Either by setting the velocity or by adding forces
Thanks! Does this code make sense?
public void Navigation(float verticalSpeed, float horizontalSpeed)
{
Vector3 movement = (transform.forward * verticalSpeed + transform.right * horizontalSpeed) * moveSpeed;
playerRB.AddForce(movement, ForceMode.VelocityChange);
}```
Also sending the settings in the Inspector.
I would recommend starting with setting the velocity
using forces is going to be a whole different beast
Also you need to remove the "freeze position" constrains on the Rigidbody
Another thing that is unexplained
your code doesn't do anything related to jumping
but your player jumps in the video
So it's not clear how that's working
presumably you have some other script doing that
we would also need to revisit that script
About that, it was actually a part of the issue: when moving along the collision, the player gains height and I have no idea why, never made a dedicated script for that, hah.
Thank you, I removed the position constraints (not putting constraints used to result in unexpected behavior when interacting with the mechanic I mentioned earlier, but I tested it now and it works fine with only the rotation constraints). The collisions get detected as they should, but the player becomes very fast and gains even more speed when going diagonally. I suppose I should be using "Mathf.Clamp" for that, right?
You should just not be using AddForce as I mentioned
that's the reason you're now dealing with acceleration
Setting the velocity directly will give you movement closer to your original movement while still respecting collisions
I did it with velocity when you pointed that out, here's how the code looks now:
public void Navigation(float verticalSpeed, float horizontalSpeed)
{
Vector3 movement = (transform.forward * verticalSpeed + transform.right * horizontalSpeed) * moveSpeed;
playerRB.AddForce(movement, ForceMode.VelocityChange);
}```
Ah damn, my bad, will fix now
It's also the same as above...
My problem isn't if it collides with the enemy or not. The debug menu says they collide.
Yeah sorry, something weird happened w my clipboard.
It works perfectly now. Thank you very much for your time and attention, I really appreciate the support and it helped me out a great deal. Have a great day!
Hello i havent opened unity for a long time so i forgot a lot of things 🙃 where is the thing to download who help with the function/component name ?
I think you want !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
ty
Kinda of a dumb question but out of curiosity for normalization rules. When you name something that starts by an acronym, do you use camel case on that or keep the acronym full in capitals letters anyways?
generally in camelcase the first word is always lowercase
disagreements come up when they're in the middle, like should something like "raw xml" be rawXML or rawXml
the latter reads weirdly, but the former can lead to ambiguities if there are multiple acronyms one after the other
I mean more if it starts with the acronym. Like something like UIManager. Would you name that as UiManager, uiManager, uIManager?? Like technically all are kinda valid
dont think anyone would really argue for uIManager in any world lol
I honestly like to give priority to the acronym, but probably is kinda wrong of me lol
eh i mean if you like that then do so
the one most important thing in regards to styling is to stay consistent
guidelines/conventions help you stay consistent with others, like with libraries and built-ins (and also helps others read it easily)
though i mean, some official APIs (not that i know of in c#) aren't consistent either lol
there's a js web api called XMLHttpRequest
ive googled it before, and kinda like following this, but apparently the convention is full capitals for 2 letters, only capital first letter for more
https://stackoverflow.com/questions/2109171/c-sharp-naming-conventions-for-acronyms
though, this is specifically for stuff that should be capitalized - should the acronym just have the first letter capitalized or the entire word?
this doesn't apply to the first word in camelcase since it's always fully lowercase
-# (intended as a footnote, but kinda sounds like im correcting you, sorry)
(though this would again apply to the first word of pascalcase)
im not really sure what you mean by "just have the first letter capitalized or the entire word" truthfully
"should capitalizing 'api' turn it into 'Api' or 'API'"
ah then yea this suggests Api
2 letter acronyms like "IO" would be capital, 3+ letters would be first letter capital
I mean, technically, on an acronym, every letter is a word, so the camel case would make every letter uppercase on those, unless it's the first letter, but then it just looks superweird. So I just make every letter uppercase
That's my logic
probably a dumb question, but fixed update doesn't work in the editor does it?
well the whole convention exists specifically because XMLHTTPRequest is hard to read. you cant immediately tell where one word ends, because its all capitals.
I need an editor window equivalent of fixed update
is there a specific reason to needing this?
yeah that's part of the reasoning behind "fully caps"
when i referred to "words" before i meant "a string of characters separated by spaces"
like for consideration in capitalizing in camelCase/PascalCase, "id" "2d" "api" "ui" "http" would be single words
I wanna play an animation at 60hz manually without using the animator window
what part here relies on fixed update? fixed update plays at 50 times per second by default
you should just use update and make a timer
"uIManager" hurts my eyes dude oh my days
Does Update() work in an editor window context?
screams in IPv4
not something ive done myself, probably better for #↕️┃editor-extensions but a quick google search shows this
https://docs.unity3d.com/ScriptReference/EditorApplication.QueuePlayerLoopUpdate.html
(i think they might want this instead but could also be wrong https://docs.unity3d.com/6000.0/Documentation/ScriptReference/EditorApplication-update.html)
this looks good. I can make my own timer as bawsi suggested with this
thank you!
Hello when i jump my player fall slowly what should i do to make him fall faster (its with rb.linearVelocity)
{
private float h;
private float v;
public float speed;
private Rigidbody rb;
private Vector3 MoveVector;
private float GCD;
public bool grounded;
public float jumpForce;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
rb = GetComponent<Rigidbody>();
GCD = GetComponent<CapsuleCollider>().height/2 + 0.15f;
}
// Update is called once per frame
void FixedUpdate()
{
h = Input.GetAxis("Horizontal");
v = Input.GetAxis("Vertical");
MoveVector = new Vector3(h, 0, v);
rb.linearVelocity = MoveVector * speed;
rb.AddForce(MoveVector * speed * Time.deltaTime);
RaycastHit hit;
if(Physics.Raycast(transform.position,Vector3.down,out hit,GCD))
{
grounded = true;
}
else
{
grounded = false;
}
if(grounded && Input.GetKeyDown(KeyCode.Space))
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
}```
You can apply negative gravity while they're in the air. Also, when using force, you do not multiply by deltaTime . . .
Your issue is this line:
rb.linearVelocity = MoveVector * speed;```
this is resetting y velocity to 0
I'm unsure why you set the velocity, then use AddForce to move. The force will cancel out any velocity applied to the object . . .
How to make human body parts do not collide with each other if a person is a prefab, and they should collide with each other
Im trying to call some stuff from a different script I made them public but its still not recognizing it.
stuff being public doesn't mean you can use them directly; you have to reference them from an instance of the given script
k figured by myself
suppose that this did work; if you had multiple instances of that component, or multiple scripts that use the same name, which one would supply the value of isJumping or whatever?
(also this is pretty basic OOP, so maybe you've reached a point where you should go learn about that further than what you already know)
void Move(int Ground)
{
if (!isChargingJump && !justJumped)
{
float targetSpeed = moveInput * moveSpeed; // Maksymalna prędkość
float currentSpeed = rb.linearVelocity.x; // Aktualna prędkość
if (Ground == 1) // Normalna ziemia
{
if (moveInput != 0)
{
currentSpeed = targetSpeed;
}
else
{
currentSpeed = Mathf.Lerp(currentSpeed, 0, Time.fixedDeltaTime * 2f); // Wolniejsza zmiana prędkości
}
}
else if (Ground == 2) // Śliska ziemia
{
currentSpeed = Mathf.Lerp(currentSpeed, targetSpeed, Time.fixedDeltaTime * 0.2f); // Wolniejsza zmiana prędkości
}
rb.linearVelocity = new Vector2(currentSpeed, rb.linearVelocity.y);
}
}
Can anyone help me.
Okay so there is situation, that player checks ground under him, and ground == 1 is normal, a lot of friction and ground == 2 is slippery, idk 0.7 friction so it's like ice
And i want for my character to slowly gain speed, like in jump king on ice, but i cant do it. Can anyone help me?
I have been trying to change this for a few hours already
Is AddComponent<AudioSource>() a relatively large performance hit?
Im working on a manager that allows multiple audio clips to be played, but caps it at 32 total audio sources. So Im having the manager create a tmp audio source when Play() is called and it rotates out the oldest ones if the limit is reached. Was planning on having AddComponent called each time a new clip is played. But Im wondering if thats too much overhead, if it might be more efficient to have prefabs instantiate the audioSource once, and pass it by reference to the manager to track
Would you say its "negligable" or "something to be considered" or "LARGE do not do this"
im making a game and when i start the game the player disappears in the pictures i showed the components i have on the player and the floor and this pastebin has the code: https://pastebin.com/hAnR2J8t
im using 2 scripts, one to move the player and jump and the other to make the camera follow the player, can someone help me fix the player disappearing?
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
im always available and if someone can help please dm me
disable the rigidbody and see if it has something to do with it
okay
we don't do dm help here
oh, mb
What's an intuitive way of iterating through all elements of a dictionary, without using foreach?
using the iterator, i guess?
what if the key is a string?
(which is what foreach does)
what about it?
Use the inspector and check the position of the objects etc. very likely it's moving out of view of the camera or maybe your camera code is moving the camera somewhere wrong
wdym?
Why not foreach? Otherwise you're foreaching over the keyset or something
Also the key type is irrelevant
because I would like to know the index of the keys
