#💻┃code-beginner
1 messages · Page 576 of 1
This avoids one of the nuisances you may have run into: needing to start the game from the correct scene
I see, are you using singletons a lot?
A fair bit, yeah. I am looking to get rid of a few of them though
e.g. the PlayerManager is going to need to turn into...multiple Players for split-screen
Singletons are great for anything that there is always exactly one of at all times
Do you have many scenes and stuff
Not a ton. One menu scene and a few levels
amusingly, the menu does not live in the main menu scene
(it lives forever in DontDestroyOnLoad)
so I have this cute little class here
using UnityEngine;
namespace Pursuit.Singletons
{
public abstract class SingletonPrefab<T> : MonoBehaviour where T : SingletonPrefab<T>
{
private static T _instance;
public static bool Safe => _instance != null;
public static T Instance
{
get
{
if (_instance == null) _instance = Instantiate(Resources.Load<T>("SingletonPrefab/" + typeof(T).Name));
return _instance;
}
}
}
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
private static void OnLoad()
{
Instance.Initialize();
}
this is in my game controller class, which is a singleton prefab
it pulls itself up by its bootstraps!
one of the first things it does is grab the main menu
// make the menu load itself
_ = MainMenu.Instance;
bit of a silly line of code..
This is very convenient for me -- it does not matter which scene I start the game in
(I do have some editor-only code that lets the GameController recognize what kind of scene in it's in -- it normally doesn't expect to wake up in a gameplay scene)
I very quickly got tired of having to start my game in the "title screen" scene
I think you can do nameof(T) btw but cool class either way
That would be a literal "T"
is it really? seems a tad dumb if so
It's a compile-time constant
but generic classes for the types should get "created" then too and thus substitute T ?
or is that not the case in c#
The identifier is still "T", even after parameterizing the type
A metaphor: nameof(x) is not 5, even if x is an int variable that has a value of 5
You might be confusing this with typeof
typeof is not a constant expression like nameof. nameof is a compile time constant like fen mentioned
typeof is runtime
i honestly just presumed nameof() would work.
wish we had constexpr shiz
Generic types aren't figured out at compile time
(pretend that AOT compilation does not exist here)
constexprs would be nice...
You can do some very, very basic stuff with const strings
private const string foo = "foo"
private const string bar = foo + "bar";
the amazing const stuff in rust makes me want a bit more for c# and unity
Hello 👋 I'll be making a 2D crossword puzzle mobile game and I'm wondering if anyone has any tutorial recommendations or anything that would make an easier start (Youtube videos, Assets to use, Game objects that I'll be needing, etc.). Thank you! 🙇♂️
aww naw. I did edit -projectsettings - physics2d - disable collision. I did this because I did not want the player to be obstructed by the food I have placed down. On collison the player's health is being checked to see if it is full or not, if not full it will not destroy the object.
I tried physics.Ignorecollision but I couln't make that work. The issue is that Now when I disabled collisions in physics2d in project settings the OnCollisionEnter2d logic is not working anymore. How can I fix that?
and eventually when unity gets .net 6/c# 10 we'll have const string interpolation
have you tried !learn ?
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
I don't see a question here
#💻┃code-beginner message edited now 😄
sounds like the food should have both a collider (to prevent it from falling through the floor) and a trigger (so the player can detect it)
these could be on different layers, too
If you disabled collisions, why would you expect OnCollisionEnter to work? Objects need to collide in order to tell the method they collided
Yeah, I thought I was smart doing it initially, until now
when I relized wat i did
is itnormal that trails wont go in the void?
I see, but I want them to never collied physically
What?
but the food does not fall throught the floor because I have no rigidbody on it
So, you want to detect when two objects overlap, without them actually being "solid" and stopping movement?
when you shoot a trail it wont go past the border i dont know how to explain
Precisely
Got a video?
Then one of them should be a trigger
the void?
you mean like anything belove y 0?
and then?
That would be how you'd detect overlapping without a physical collision
Make one of them a trigger and use the OnTrigger methods instead of OnCollision
I see. I could have ddged this too I relized. But thanks, will try
Pay attention to the parameter type that OnTriggerEnter expects
as well as whether this is 3D or 2D
this walks you through everything
anybody know why this player health script isnt working?
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Also, what specifically isn't working
Wont let me modify it
Did you try opening it
What won't let you modify what?
Okay, what about it
Doesn't say anything like "max health" or "health" in the inspector tab right there
Do you have any errors
Should let me modify it right there
Not sure haven't tested yet
So, go look
we are talking about compile errors here, which will be listed in the console window
we can all see that but you need to check the compile error to know yourself why its wrong
ideally your IDE would help you out
!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
I use VS code so il check that
using UnityEngine;
public class Playerhealth : MonoBehaviour
{
public int maxhealth = 10;
public int health;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
health = maxhealth
}
public void Takedamage()
{
if (health < = 0)
{
destroy (gameObject)
}
}
!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.
!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.
what the hell happened to your formatting 
YouTube tutorials suck don't they? 
plz fix your vs code now so it shows the errors in the file
only 1 of them works. choose carefully
(they all work the same lol)
please 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
!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
ops. click the one for VS CODE
If you can find me a Youtube tutorial that tells you to write code like that I will deadass venmo you $10 on the spot
you have at least 4 errors here
That's exactly why I came to #💻┃code-beginner
This is not an issue with a Youtube tutorial. This is entirely of your own doing
go configure your ide
I started unity like 3 days ago
You're missing a closing curly brace } at the bottom of the file. Destroy should have a capital D.
let them configure the IDE first
then it'll tell them the errors
🙏 please we urge you to fix your ide it is soo important
!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
Yes fix the ide it'll help you by pointing out the errors. Those errors should also appear in unity itself in the console section.
code makey program
True but as an absolute beginner there is something to be gained by learning without a language server
the thing you type code in
a lot of hours wasted, more like
guys is this move script good
(╯°□°)╯︵ ┻━┻
as a beginner they likely aren't going to figure everything out themselves
a language server gives immediate feedback
not really, no
you can check isGrounded directly instead of comparing it to true
you can use CompareTag instead of comparing the string tag directly
AddForce with ForceMode.Force is already time-dependant, and it should be done in FixedUpdate. you might want to use ForceMode.Impulse there, and also remove deltaTime.
you might want to use GetKeyDown instead of GetKey.
isGrounded should probably not be public/serialized
"No problems have been detected in the workspace. "
if so then you haven't configured it completely
there's very obvious issues in the code you showed
close the file and open the file again from unity (double click script in project browser) if you have now configured vs code correctly
oh yeah also that
thanks mate
The problems just aren't appearing I'm not sure if I'm forgetting something or not
GAH
god please do not take pictures of screens
there aren't enough commands in this server to describe how much my eyes hurt right now
Jesus fucking christ how many times am I going to have to post !code before you read it
📃 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.
!screenshots
No
Be mindful, if someone requests your code as text, don't send a screenshot!
well, they are at least trying to demonstrate that the IDE is malfunctioning
in that case, use a screenshot, not a photo
Hmm, Apparently I do have problems because all compiled errors must be fixed before testing.
you may also want to use a Raycast for the groundCheck. otherwise, if a wall is tagged as ground, grounded will be set to true (even if they're in the air and touching the wall)
That's fair ill agree with that. A lot of my muscle memory and what I have memorized is from early on when I coded without a language server. I realized that a lot of the things I "learned" after I started using them I didnt actually know because I was reliant on the auto complete.
So, configure your !ide, look at the things underlined in red, and fix them
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
Nothing is underlined in red though?

because either the language server is waiting on a download or something or you havent' configured it properly
That's why that was the second part of what I said to do
If you didn't follow all of the instructions for VS Code linked above, do that now.
@spice dawn if you close vs code fully and then in unity do Assets > Open c# project, does this make it work?
lemme try
if you followed the configuration steps it should open the code project and make shit work
Now I see assets, library, logs, packages, project settings, temp, user settings
ah, you didnt open the project folder before...
now go find your script! (Ctrl + T to type search, CTRL + P to file search)
i wasnt sure if vs code was just opening the file on its own as i know vs will open the sln from a script file open
since vscode isn't an ide in itself it also supports opening singular files outside projects ("open folder")
hi guys i putted 3d model into unity but it wont put itself into working window whats the problem?
doesn't sound like a code issue, see #🔀┃art-asset-workflow or #💻┃unity-talk perhaps
Have you tried Dragging it in
yes but it doesnt let me
You imported it in correct?
i didn't really understand what should i do with isGrounded bool to be honest, i changed in collision void from gameObject.tag to gameObject.CompareTag
yes
@elfin canyon @spice dawn this isn't the right channel to discuss that issue
mb
i mentioned it a few times, which change are you talking about
Found it, opened it, but it brought me back to just a script with no errors?
you sure you did all the set up?
make sure to give it a bit to think
sorry if i am bohring to you, but i started programming few weeks ago, this is the changes i made
Where is analysis i cant even find it
If the "Visual studio editor" unity package is up to date in project, you set your editor to "Vs code" in preferences and install the Unity extension in vs code it should work.
this includes troubleshooting steps for vs code configuration: https://unity.huh.how/ide-configuration/visual-studio-code
ok done
Let me open vs code
thats great but the website linked to in the ide info box we kept sending should have explained this too
Hi, me again. I have this script that gives you a 3x income boost, how could I make it so when I buy an upgrade the increase in multiplier get's 3x'd aswell? Idk how to explain it better basically when I upgrade multiplier gets increased by normal value not the 3x'd value and idk how to do it really
multmult = 3; xt.text = $"3x Active! {Mathf.Round(timero2)}s left"; if(!alreadymulted) { ms.acm *= multmult; ms.mult *= multmult; ms.p4m *= multmult; ms.p5m *= multmult; alreadymulted = true; alreadydivided = false; timero2 = 30f;
ms is MainScript, acm/mult/p4m/p5m are the multipliers from different upgrades, aldreadymulted is just checking if the values have already been multiplied, alreadydivided is set to true once timero2 gets to 0 and the values are divided.
I should be able to do this I just want to get some of your ideas on what would be the most optimized way to do it
!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
could you not spam the commands?
go through this link: https://unity.huh.how/ide-configuration/visual-studio-code
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
Why do you keep re-using the command
Get to it quicker
Just keep the tab open
scroll wheels are cringe
ok am I just plain out stupid
(Probably)
But anyways what the hell I'm on the same page as I was 20 minutes ago
You should probably not ever actually modify the base values. Just store the value and the multiplier, and whenever you use those values, do the math on the spot
Im assuming I could just access multmult via MainScript, make it so upgrading doesnt just add 1 but it adds multmult then after dividing the values when 3x runs out set it back to 1?
Basically, instead of doing ms.acm *= multmult;, you'd keep ms.acm as it is, and wherever you use it, you'd use ms.acm * ms.mult
If its working you now have help in the editor to write code and fix code easier
It says I have compiler errors but again, it doesn't show any on idc
Then you're missing some steps on the configuration
Okay what about all the other steps
btw you should not configure IDE with compile errors
make sure you comment those out first if you have any
press the regenerate button under that bit it may help
looks configured on this part, you need to try closing VSC regen project files button on that page then open script again from unity double clicking, it either will work or spit out .net sdk error
Do I need any of the external script editors file boxes ticked off or no? I have the default ones
only the top 2
nah dont bother changing it. The regen button will re make the files needed for visual studio code or other IDEs to correctly open your project.
Usually code recompile does this but your code is brokey
yeah, if you had to install the "Visual Studio Editor" package, none of its scripts will actually have compiled
note if you still have compile errors, it will not work no matter wat
since there is currently a compile error
you can just comment out everything in the script to let Unity compile
how do I do this
delete the file
By commenting the lines out
can it regen in safe mode?
note that this is only true if the visual studio editor package was not installed prior to configuration. that is the only thing that is prevented from actually working when there are compile errors in the project
if it can't compile its not going to be able to attach well to vsc
yea true
its cause of packages, it had to connect and if you cant install it wont be able to
Hullo, I am trying to figure out how to check either
- a boolean/value of a sibling in the heiarchy tree
or - a boolean/value gameObject (Such as the player)
is this possible?
I am trying to prevent my truck from picking up 2 crates, limiting it to picking up only one at a time.
btw you could store the actually gameobject into a variable
like the currentObject, if its null then you have free space and you can pick it up
What do you mean by that?
dont you have a pickup script?
Like refer to itself as currentObject?
What is the line needed? I have been searching for it for a while
show how you currently pickup the cubes
with script*
I admit it's a really messy code. I have just been hacking away without refactoring yet
its totaly fine
this is beginner channel, we all been there
would be easier to read if you sent via links lol
👇
📃 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.
Use Scriptbin to share your code with others quickly and easily.
oh the cube itself has the pickup logic
Super messy, and should be redone, with bits and bobs all over the place
Should I redo it such that the Truck has the script logic?
@signal pollen based on what i just saw, the collectable hides and marks it self as collected. You want your truck/player script to track what collectables its holding so you can hold only one.
e.g.
Player player = hit.GetComponent<Player>();
bool pickedUp = player.TryPickUp(this);
if(pickedUp) //do stuff
I wouldve probably done it the opposite so its easier
but basically you can still access player from this
Yeah I am figuring that now
Player player```
is a thing?
so you can store the cube itself and dont even need bools to track, and you can store cube to do other things with it
GameObject theCube
void OnTriggerEnter(Collider col){
if(col.CompareTag("Cube") && theCube == null)
//pickup cube
}```
Substitute it with your own type or a new script. Its just an example
oh
Assuming you have a class named Player, yes
I see
Maybe redoing the scripts as whole is the way to go then\
I've done this very messily lol
for example:
public class Player : MonoBehaviour
{
private Collectable heldCollectable;
public bool TryPickUp(Collectable collectable)
{
if(heldCollectable == null)
{
heldCollectable = collectable;
return true;
}
else return false;
}
}
there is probably no reason for each cube to be using OnTrigger methods for each one, rather than player itself has pickup script
Yeah that is true
That is true, the truck/player is the better place to do the picking up logic
I used this collectible script cos the Junior Programmer course by Unity did that
something like this basically but maybe call it CollecatiblePickup or something more specific to its responsibility
When instead the correct/smarter thing to do is to attach the collectible script from the player persepective
yeah its common
Okay! Time to refactor the whole thing. I have been avoiding it for too long
Thank you guys
(Although I could just do with sleep)
no sleep only code
fun-free zone 😛
no fun only code
'SceneManager' does not contain a definition for 'LoadSceneAsync' and no accessible extension method 'LoadSceneAsync' accepting a first argument of type 'SceneManager' could be found (are you missing a using directive or an assembly reference?)
im using UnityEngine.SceneManagement
Most likely you made your own class named SceneManager
Try UnityEngine.SceneManagement.SceneManager.LoadSceneAsync(...)
or rename your SceneManager class
(I bet this code is probably inside your class named SceneManager in fact!)
Yeah the class is named SceneManager
so am i gonna have to write out UnityEngine.SceneManagement every time?
I mean for one I don't recommend modifying the code inside packages in the first place
this would also happen if you had a using directive for the namespace that Fishnet's SceneManager is contained in
you can use an alias:
using Whatever = Some.Specific.Thing;
You could also do:
using UnitySM = UnityEngine.SceneManagement.SceneManager;``` or one of the other suggestions I mentioned above.
Look closely at the code
they have in fact ALREADY aliased it for you
So you can just use UnitySceneManager
var scene = UnitySceneManager.LoadSceneAsync(...)
The name 'UnitySceneManager' does not exist in the current context
Well it would be nice if you shared what the current context is with the class
My impression was that you were writing code inside the Fishnet script
its inside a network behaviour
note how that code does not have the same using alias
Ok so then you need to add an alias as we mentioned
or write out the fully qualified name
pick one
There are three examples of creating an alias above
If you had added using UnityEngine.SceneManagement; , you'd have gotten an error when trying to name SceneManager -- it's unclear which type you're trying to refer to
UnityEngine.SceneManagement.SceneManager vs. FishNet.Object.SceneManager (presumably)
im just gonna use this one
using UnitySceneManager = UnityEngine.SceneManagement.SceneManager;
that async is looking wonky
looks like it loads the lobby scene again before then going into game
isn't progress already normalized, why /0.9f
it only progresses to 90% if allow scene activation is false. but it seems that the issue is that it does most of the loading in a single frame (or at least in less than 100ms) so it fills up to that point, then because it has finished loading by the time the delay has ended it continues without filling the rest of the bar, which leads directly to a 2.5 second wait
It should be <= 0.9f instead of < 0.9f
you're never going to see a full bar because it will never update the fillAmount when it's == 0.9f which would be a full bar with this code.
how come when i spawn a clone game object and i put in update
Vector2 dir = Vector2.left;
body.linearVelocity = dir * moveSpeed;
but it wont move
have you confirmed that code is running? do you have any errors? are there any colliders blocking the object? you gotta provide more details
my code is working and correct but maybe its the pipe cuz i put 3 object thoghether?
Several possible reasons:
- The code isn't on the object
moveSpeedis zero- The object is moving, but so is everything else so you can't tell
- You're actually asleep and hallucinating the computer right now. Please wake up, we all miss you.
- You are getting an error preventing this code from executing
- Your object is gigantic and it's moving an imperceptibly small amount
lmao
Basically, more information is required
number 4 for sure
and also the box coliders shuldnt be the problem they arnet tuching
What is body?
Presumably, a rigidbody of some sort, but which object has it?
which object has this script on it?
the clone pipes
Can you show the inspector for this script on your prefab
You'll obviously have to change some things around (e.g. I am invoking events that you don't have here and you're using async await vs a coroutine), but this is a snippet from my own async scene loading script which works well with progress bars. In my case I have the loading screen UI subscribe to these LoadSceneProgress and LoadSceneComplete events rather than coupling them together.
var asyncOperation = SceneManager.LoadSceneAsync(sceneName, loadSceneMode);
if (asyncOperation != null)
{
while (!asyncOperation.isDone)
{
var progress = Mathf.Clamp01(asyncOperation.progress / 0.9f);
progress = Mathf.Max(progress, fakeProgress);
LoadSceneProgress?.Invoke(progress);
yield return null;
}
LoadSceneComplete?.Invoke();
}
ah there's also this fakeProgress thing I have... You can ignore/delete that line unless you want me to explain it :3
show the entire PipeMovement script
Show !code for the script
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
i think im just an idiot
let me try something for 1 min
yea im an idiot i forgot the
body = GetComponent<Rigidbody2D>();
pay attention to the errors in your console instead of ignoring them
i was staring at my screen for like 10 mins until u asked me to show the full script
is there any way u could put it in like hastebin
cause im on my phone now
and its like multiple lines and shit
or paste of code or any website
var asyncOperation = SceneManager.LoadSceneAsync(sceneName, loadSceneMode);
if (asyncOperation != null)
{
while (!asyncOperation.isDone)
{
var progress = Mathf.Clamp01(asyncOperation.progress / 0.9f);
progress = Mathf.Max(progress, fakeProgress);
LoadSceneProgress?.Invoke(progress);
yield return null;
}
LoadSceneComplete?.Invoke();
}
how about just plain text reply
that’ll do thanks
i saw some people stopping the scene from loading
by setting something to false i dont remember what it was
and when it finished they set the bool to true
it was allowSceneActivation
why arent u using that there?
!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.
tell that robot who's boss
lmao
I think sllowSceneActivation might be a new thing in Unity 6...? Or its just something I've never found I needed.
ah okay
yeah I've just never bothered touching it
Looking at the documentation though it looks like you will need it to be true for the snippet I added
Otherwise you'll get stuck in that while loop
because isDone will never be true
unless at some point you change allowSceneActivation back to true in the while loop in order to break
I guess you could set allowSceneActivation back to true if progress >= 0.9f 🤷
But then I don't really see the point in touching it at all
Ahh okay in the example in the documentation they show a case where for example you'd want the player to press a button after loading finishes in order to activate the scene. That's what it's for. If you just want it to load when ready then don't bother touching it.
// hi
// hello!
i just followed a tutorial and when i go to pick the object up that i want it just applies force to it once and doesnt make it float, any help?
Post your !code in a non video format
📃 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.
using JetBrains.Annotations;
using UnityEngine;
public class PickupObject : MonoBehaviour
{
public float pickUpForce = 150f;
public float pickUpRange = 5f;
public LayerMask isPickable;
private GameObject heldObj;
private Rigidbody heldObjRB;
public Transform holdArea;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
if(Input.GetMouseButtonDown(0))
{
if(heldObj == null)
{
RaycastHit hit;
if(Physics.Raycast(transform.position,transform.forward, out hit, pickUpRange))
{
Pickup(hit.transform.gameObject);
}
}
}
else
{
Drop();
}
if(heldObj != null)
{
MoveObject();
}
}
void Pickup(GameObject pickObj)
{
if(pickObj.GetComponent<Rigidbody>())
{
heldObjRB = pickObj.GetComponent<Rigidbody>();
heldObjRB.useGravity = false;
heldObjRB.linearDamping = 10;
heldObjRB.constraints = RigidbodyConstraints.FreezeRotation;
heldObjRB.transform.parent = holdArea;
heldObj = pickObj;
}
}
void MoveObject()
{
if(Vector3.Distance(heldObj.transform.position, holdArea.position) > 0.1f)
{
Vector3 moveDirection = (holdArea.position - heldObj.transform.position);
heldObjRB.AddForce(moveDirection * pickUpForce);
}
}
void Drop()
{
heldObjRB.useGravity = true;
heldObjRB.linearDamping = 1;
heldObjRB.constraints = RigidbodyConstraints.None;
heldObjRB.transform.parent = null;
heldObj = null;
}
}
else
{
Drop();
}```This looks suspicious
What do you mean by "it doesn't make it float"?
i can add a video
You could probably just explain in a sentence or two
It would drop the object unless you click the mouse button every frame, at superhuman speed
Do you mind linking the tutorial?
yeah
Lets learn how to pickup and drop objects in Unity. Objects with a Rigidbody component attached can be manipulated like the portal style physics game mechanics. The system can easily be modified to only pick up objects with a certain tag or adjust the speed at which objects are moved. Written in C# and all the content can be found on my Patreon ...
I'm assuming gravity is occurring
yes, what i meant was how when you pick up something in a game like portal or half-life it hovers there in front of you, as if you were making it float
Should it fall immediately after you pick it up? If not, when should it fall?
^Yeah, this is in the wrong spot
its supposed to fall after you click the mouse button while its already being picked up
You'd probably want that else inside that if statement: when checking for null
Did you save?
here we go
thank you
i just noticed something really odd
have you ever heard of the game superliminal?
the object im picking up is changing size based on my perspective
i think your right
its still doing it, its alright though i think ill be able to find a fix
could you show whats happening
the scale on that cube is crazy large
the giant wall or the one im picking up
I'd unchild the cube and keep the scaling uniform
The selected cube isn't the one they are moving
Actually didnt read the problem but I assume it's being added as a child when moving the cube, but the parent scaling it applying to the cube and it's making it odd-shaped
the cube is being parented to an empty object that stores the hold position
Maybe im hallucinating, but looks like the shape of it is changing but could just be perspective
Oh you did mention it here. Yeah I'd keep an eye on the parent scaling if not the object itself
something's being changed, and ideally keep your scaling uniform
do you mean keeping my scaling uniform as in not making giant objects
hey guys, can you tell me why my dash mechanic isnt working? for some reason it wont move in the x axis
I already explained what it means
oh yeah sorry
(1, 1, 1) = uniform
(3.5, 3.5, 3.5) = uniform
(1, 2, 3) = not uniform
also if you parent an object at runtime you need to set the optional bool to keep its world orientation if the parent has scaling other than 1, otherwise it'll act upon the child object
ok the scaling issue is fixed
or just not scale the parent at all
If you print out the velocity afterwards what values are you getting
its also not moving with my character which is odd
Basically the issue im having is I need the camera movement script to rotate the player body but only side to side so it doesn't rotate the body to be parallel with the ground lmao I'm on the verge of a breakthrough to do it but i just can't seem to grasp the process
and lemme go grab the code hol up
alright ill try that.
{
public CharacterController controller;
public float mouseSensitivity = 100f;
float xRotation = 0f;
float YRotation = 0f;
void Start()
{
//Locking the cursor to the middle of the screen and making it invisible
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
//control rotation around x axis (Look up and down)
xRotation -= mouseY;
//we clamp the rotation so we cant Over-rotate (like in real life)
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
//control rotation around y axis (Look up and down)
YRotation += mouseX;
//applying both rotations
transform.localRotation = Quaternion.Euler(xRotation, YRotation, 0f);
}
}
you're probably overwriting the velocity somewhere else in code. Set velocity isn't accumulative, only forces are
i made the reference to the character controller but how do i exactly rotate it like the bottom process``` //control rotation around y axis (Look up and down)
YRotation += mouseX;
//applying both rotations
transform.localRotation = Quaternion.Euler(xRotation, YRotation, 0f);```
The whole thing is a bit flawed, you should not use parenting with dynamic rigidbodies.
You can try setting the rigidbody isKinematic To true when you pick it up and to false when you drop it. This won't use any physics though really.
Or you can get rid of parenting and move the picked up rigidbody with a Joint or some forces.
Ignore the poor discord format lol
```cs
...
```
almost had it lol
huh?
float
int
formatting
lmao
put cs after the ``` to make it format correctly
but anyways how could i replicate this bottom half but for the player controller to rotate side to side only
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
//control rotation around x axis (Look up and down)
xRotation -= mouseY;
//we clamp the rotation so we cant Over-rotate (like in real life)
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
//control rotation around y axis (Look up and down)
YRotation += mouseX;
//applying both rotations
transform.localRotation = Quaternion.Euler(xRotation, YRotation, 0f);
}
}```
you should not be multiplying your mouse inputs with deltaTime btw
it was part of a tutorial i was watching for my old project lmao this is just a reused script for a new project
the brackys tutorial ? yeah that tutorial is shite lol
it was a survival game tutorial from someone else lmao
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
//control rotation around x axis (Look up and down)
xRotation -= mouseY;
//we clamp the rotation so we cant Over-rotate (like in real life)
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
//control rotation around y axis (Look up and down)
YRotation += mouseX;
//applying both rotations
transform.localRotation = Quaternion.Euler(xRotation, YRotation, 0f);
}
}```
just 2 letters 
that is just as shite then
okay but ignoring the poor choice of delta time , i still don't know how to properly replicate the bottom half for the character controller 🤣
could i just replace "mouse" with "controller"? or would that not work
"side to side" is y rotation
yeah its this half
//applying both rotations
transform.localRotation = Quaternion.Euler(xRotation, YRotation, 0f);
}
}```
yeah?
If you only want y rotation, remove the x rotation
YRotation += mouseX;
//applying both rotations
transform.localRotation = Quaternion.Euler(xRotation, YRotation, 0f);

how can i disable a script?
script.enabled
or this little tick on the left
ohhh i see, thanks!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseMovement : MonoBehaviour
{
public CharacterController controller;
public float mouseSensitivity = 100f;
float xRotation = 0f;
float YRotation = 0f;
float YBodyRotation = 0f;
float XBodyRotation = 0f;
void Start()
{
//Locking the cursor to the middle of the screen and making it invisible
Cursor.lockState = CursorLockMode.Locked;
}
void Update()
{
float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
float bodyX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
float bodyY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
//control rotation around x axis (Look up and down)
xRotation -= mouseY;
XBodyRotation -= bodyY;
//we clamp the rotation so we cant Over-rotate (like in real life)
xRotation = Mathf.Clamp(xRotation, -90f, 90f);
XBodyRotation = Mathf.Clamp(xRotation, 0f, 0f);
//control rotation around y axis (Look up and down)
YRotation += mouseX;
YBodyRotation += bodyX;
//applying both rotations
transform.localRotation = Quaternion.Euler(xRotation, YRotation, 0f);
transform.localRotation = Quaternion.Euler(XBodyRotation, YBodyRotation, 0f);
}
}
still failed the format im sorry T_T @rich ice
atleast you tried. that's what really matters 
move down the ``` at the bottom by 1 line
should fix it
but i think i got it? i just needa know how to connect the X and Y BodyRotation to the controller
You added extra spaces after cs
There we go
there we go!
got there in the end lol
but how can i make the (X and Y)BodyRotation be the thing that actually rotates the controller?
well the body...
but yk what i mean lol
you could make the mesh and the controller separate
the camera which is the child of the game object that has the controller
you'll see the reference in the script at the top
and it's already connected to the game controller
is there a very particular workflow for creating intro screens, logos and initial loading stuff? otherwise i'm winging it
but i needa know how to actually make the controller be the thing getting the rotation from Bodyrotation
those are 3 different things
but, you're probably looking for the animator
(timeline is also a thing that exists. i dont exactly know what it does. but, it exsits.
Hi, unity noob trying to make a simple game, I have a rocket spaceship that can move left and right and I want the spaceship to rotate 45 degrees to each side as I move. I'm currently using input.getaxis(horizontal) with transform.translate and transform.rotate but the ship continues rotating as I move when I want it to stop at 45 degrees. I've looked up mathf.clamp and eulers and all that but its very confusing. Could someone help me out please?
is it 2d or 3d?
3D but moves in 2D
ship moves upwards on its own and player can only move left and right
have you tried setting the rotation?
Mathf.Clamp(xRotation, -90f, 90f);
so something like
transform.rotation = Quaternion.Euler(45 * input, 0, 0);
lool
whats the difference between transform.rotation and transform.rotate? Unity tutorial uses transform.rotate but everyone else online ive seen uses transform.rotation
transform.rotate adds to the rotation
transform.rotation sets it (and allows you to read it)
https://paste.ofcode.org/FU3MxwBmBrU2xiwdAMwY4M could someone help me rotate my character towards the direction of the velocity i know you can use mathf.movetowardsangle but i have no idea how to apply it
transform.forward = rb.velocity.normalized
(or atleast thats the quick fix, im still reading the code)
yeah i think this should work fine (unless you want to add smoothing, that requires a little extra code)
thank you let me try that real quick
@rich ice i was wondering why my target dissapears when i tried adding this am i doing something wrong
changing transform.forward should only change the rotation. not position
something else must be causing it
ok ill try changing it thank you

Hi peps. 
your code also looks a little messy. you can try taking a look at this script, that i made, for reference if you need it. should have every method you could want to use
https://hastebin.skyra.pw/vocegoxada.pgsql
hello 
What is the actual "forward" direction of your character?
Select it and show us with gizmos in local mode
oh right good point. the pivots could be messed up
If it moves on the XY plane I would expect it to be transform.right or .up
thank you for the script
YOOOooo lets goo i did it lmao
nice job 
so basically all i did to fix my issue so the body doesn't become parallel to the floor is, the parent which is holds the game controller is the one with the mouse movement for looking side to side and the camera itself is the one that looks up and down
probably not the "best" method but if it works then i guess i don't gotta fix it 🤣
the reason the body looking straight down was bad was because it made it so when you jumped and walked backwards..... your backwards was in the air....
I made this stuff using IPointer(Enter, Exit, and Click).
How do i make it so it detects if you clicked something outside of that window (so the dropdown can close)? Preferably by not checking a mouse input every frame.
so you could jump even higher by jumping then looking down and then holding S
it was a very weird bug lmao
so long as it work 
huh, yeah that is weird lol
well it makes sense though in a way
cause when you look down, your back is in the air....
so moving back... was moving into the air lmao
the gravity eventually brought you back down at a speed you couldnt fight but like...
you're probably better off checking if the window is in focus, than mouse inputs. i dont think unity can read mouse inputs if the window isn't in focus
still being able to jump 2x higher than normal wasn't a great feature lmao
oh yeah, that's a pretty common bug iirc
next up on the bug bingo, 3x jump height 
now i coulda just patched the bug with different methods probably
but this way is more beginner friendly lmao
I could try receiving mouse events straight from canvas then invoke a unity event? 
oh wait, outside of the in-game window
thought you meant the game window as a whole
should be fairly simple just need to refer to the player movement script and increase the player movement score when shift is held down else it is put at it's set value
now as for changing values via script from another component is....
Yeah.
I looked into OnApplicationFocus and it's not the right thing.
a different issue for me to figure out lol
im not entirely sure how to fix that. i've never actually used the IPointer stuff
Oh, it seems like Unity depreciated IPointer stuff. Or it seems like it.
Into unity 6.
does unity has a function or a solution that allows me to swap runtime animation in animator states? the reason is some others think making a lot of states in animator for different animation clips is unnecessary work basing on their UE experience, so they wonder if they could swap in-out animations in same states to play a lot of different animation in runtime, which is a part for the skill cancel system. overrideController would be a solution but i heard that has a heavy performance hit when used a lot, is there any better approach for such situation?
Link all animation states to Start and End.
And just use flags.
You set the flags in code.
Flags can be vector2, floats, bools.
And the condition for each state can be whatever you want.
ehh i already ran into an issue 2 lines into coding lmao
float shift = Input.GetKeyDown(KeyCode.LeftShift);
why is it already underlined
lmao
The guide I remember might be outdated, but yes.
oki, thanks
How would I get the player to move with the camera
Im using CM freelook rn but I want to move my camera and the player to go twards that way
(technically) not a code question
use a position constraint or parent the camera to the player
Is cinemachine good? I never bothered with that.
using UnityEngine;
public class Run : MonoBehaviour
{
public PlayerMovement PlayerMovement;
// Start is called once before the first execution of Update after the MonoBehaviour is created
void Start()
{
}
// Update is called once per frame
void Update()
{
float run = Input.GetKeyDown(KeyCode.LeftShift);
{
if run = true;
PlayerMovement.speed = +5;
}
}
}
where problem at? xD
i've only ever really had problems with it. good for cinematic shots but useless for something like an FPS
there are beginner c# courses pinned in this channel, you should start there
cinemachine's camera controls will likely be better than whatever you may be able to write. and a lot of stuff JustWorks™️
jokes on you! I did it
sorta lmao
void Update()
{
bool run = Input.GetKeyDown(KeyCode.LeftShift);
if (run)
{
PlayerMovement.speed = PlayerMovement.speed + 5;
}
}
}```
jokes on you! if you don't learn the basics you're going to fail at making a complete game!
I'll submit to it at some point, been watching a few tutorials and i did start the course but ehh been playing around with 3D movement
You want speed to increase by 5 every frame when you hold shift?
Is the speed being set every frame?
Oh and it's using GetKeyDown so it doesn't even make sense
Unless you reset it on keyup
that was the start of the code lmao
now it's functional
bool run = Input.GetKeyDown(KeyCode.LeftShift);
if (run)
{
PlayerMovement.speed = PlayerMovement.speed + 5;
}
bool NoRun = Input.GetKeyUp(KeyCode.LeftShift);
if (NoRun)
{
PlayerMovement.speed = PlayerMovement.speed = 15;
}```
PlayerMovement.speed = PlayerMovement.speed = 15;
lol
shhhh
bool run = Input.GetKeyDown(KeyCode.LeftShift);
if (run)
{
PlayerMovement.speed = PlayerMovement.speed + 5;
}
bool NoRun = Input.GetKeyUp(KeyCode.LeftShift);
if (NoRun)
{
PlayerMovement.speed = 15;
}```
bool run = Input.GetKeyDown(KeyCode.LeftShift);
if (run)```
This could be shortened to:
```cs
if (Input.GetKeyDown(KeyCode.LeftShift))```
using UnityEngine;
public class PlayerMovement : MonoBehaviour
{
public float moveSpeed = 5f;
public Transform cameraTransform;
private CharacterController characterController;
void Start()
{
characterController = GetComponent<CharacterController>();
}
void Update()
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
Vector3 inputDirection = new Vector3(horizontal, 0f, vertical).normalized;
if (inputDirection.magnitude > 0.1f)
{
Vector3 cameraForward = cameraTransform.forward;
Vector3 cameraRight = cameraTransform.right;
cameraForward.y = 0f;
cameraRight.y = 0f;
cameraForward.Normalize();
cameraRight.Normalize();
Vector3 moveDirection = cameraForward * inputDirection.z + cameraRight * inputDirection.x;
characterController.Move(moveDirection * moveSpeed * Time.deltaTime);
Quaternion targetRotation = Quaternion.LookRotation(moveDirection);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * 10f);
}
}
}
Why isnt this working
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/, https://paste.ofcode.org/, https://paste.myst.rs/, https://scriptbin.xyz/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
also be more specific than not working
ngl i was trying to go that route at first but didnt use the parenthesis that would explain why it wasnt working lmao
It says it needs to derive from monobehavior
but it works all the same so hey I'm satisfied lol
You need to save your code and fix any compile errors in the console
lowkey proud i figured out the run ability lmao
jokes on you again! I can't fail to script if I can't come up with an idea to script! (yes i said this because i just ran outta ideas lmao
this is honestly just a learning project i got honestly, just kinda coming up with ideas to slap in and code, learning by doing which ultimately probably isn't the best method with all these courses and stuff but I wanna just kinda play around with some coding and figure it out the hard way lmao if something doesnt work i search it up ig
yo i just had a weird thing happen
i added something relatively small that should have just saved a text based on an outcome (win or loss) of my gamescene using PlayerPrefs, and then used that to set a text in the gameover scene
and it proceded to not let me play my gamescene, every time i press the play button unity just freezes and stops responding so i have to close it with the task manager
i tried deleting that script (and a bunch of others that were my most recent to try work back to the issue)
but it hasnt done anything its still freezing, and now ive lost scripts for no particular reason
would anyone have any ideas to fix, or any questions i could try to answer to help narrow down a solution?
please im desperate
You probably wrote an infinite loop
it was a few hours ago at this point so im not sure exactly the order of things i added but i have a general idea and have removed pretty much everything ive added today, and everything from previously was working fine
check the newly added code for while or for loops
yep you wrote an infinite loop 😛
Why does your class derive from PlayerInput?
No, the class should not be static
just the instance
Because you made the instance variable of type PlayrerINput
If it's not derived from MonoBehaviour it won't be a component
You want something like this:
public class MySingletonThing : MonoBehaviour {
public static MySingletonThing instance { get; private set; }
public readonly PlayerInput input = new();
void Awake() {
instance = this;
}
}```
Technically not really no
But you couldn't use Awake in that case
You could do something along these lines:
public class MyInputHolder {
static MyInputHolder _instance;
public static MyInputHolder Instance {
get {
if (_instance == null) {
_instance = new();
}
return _instance;
}
}
public PlayerInput Input { get; private set; } = new();
}```
yes
This would be not as a MonoBehaviour
It's not better it's different
It does mean you wouldn't have to put it in the scene though
But you would need to manage eveything about its lifecycle manually
This is more of a typical plain C# singleton
vs a Unity singleton
it's short for new PlayerInput() yes
it's called a target-typed new
what part gives you what error
You seem to be accessing playerInput in OnEnable before it's assigned
just based on that screenshot
OnEnable runs before Start
You could use OnEnable, you just can't use the variable before you assign it
Ok so you're using the MonoBehaviour way
Rule of thumb here is that you should not access other components in Awake or OnEnable
because there's no guaranteed order for that
gInput's Awake is running after the other script's
Did you actually put an instance of gInput in the scene?
yes
It needs to be attached to a GameObject in the scene
That's... a weird setup, to be honest
but you'd have to show the whole setup
These errors seem to be in a different script
Oh yeah this:
public static gInput instance { get; private set; }
public readonly PlayerInput input = new();
void Awake()
{
instance = this;
}```
Should be changed to:
```cs
public static gInput instance { get; private set; }
public PlayerInput input { get; private set; }
void Awake()
{
input = new();
instance = this;
}```
this will fix the first error, and the first error was causing the instance not to get assigned I would say
that's usually how it's done. you can have a separate GameObject for each singleton or pile them all on the same one. using a separate GameObject for each gives you more freedom and ease of setup, design-wise . . .
@cosmic dagger can I ask you a question
you have 5 secs . . .
though, it's easier to just ask the chat bcuz anyone could help answer . . .
#📖┃code-of-conduct btw you shouldn't ping someone you're not in conversation with
Oh I’m sorry I’m just really new to this whole thing and everytime I go to load a project it says failed to decompress template and it won’t load I have tried moving the path file so it wasn’t so long and I deleted and redownloaded unity 4 times tonight trying to get it to work
check file size on disk
and probably check the logs
What do you mean @rich adder
not code question btw this goes in #💻┃unity-talk
I’m like brand new got unity today I just have a game idea I wanna make it’s super simple
have you used a computer before?
Yes obviously but not for game development
but what I suggested has nothing to do with game development
Wym lol isn’t that everything unity is lol
checking if you have enough disk size on pc is a basic usage of computer
I mean I have a 1tb hard drive? I’m not very tech savvy
since you asked what do you mean, thats why I asked lol
yes total size but what about free space
I have a very specific idea that I want to emulate an old toy from the early 2000s called cube world I want to make a modern version for computer and 337 gigs free
it would help if you showed details rather than having to ask 20 qs
Do you remember that toy by chance looks like this
I’ll show you a picture of what it is doing one sec
Sorry it’s going to make me reinstall the editor hopefully that fixes it
Might want to upload an image of a common format like Jpeg or PNG that are displayed in the discord. No one is gonna download that file to have a look
Oh my bad I didn’t know it was like that lol one sec
I was wondering why it was like that
It’s a super simple concept one stick figure per cube when cubes are connected stick figures can flow in between them and each cube has a unique character action and appearance
How would you code something like that
there are quite a few systems involved
probably should not be your first project if you're new lol
start with basic projects to gain xp, and with unity learn website lessons
But it is like the one thing I wanna do lol cause I have not found anyone who has emulated this toy lol and I just wanna play it again and live out the nostalgia
Like I’m just trying to do this for a personal thing
It's also not entirely clear how you want to implement it. Are you gonna need these cubes(or an upgraded version of them) to run the game?
yeah the idea sounds good, no one saying dont go for it, just build up the mechanics to it by learning smaller things
games are just a bunch of systems mushed together
No no I want it to be like a fallout shelter lay out game @teal viper where you can stack them like rooms
I want it to be a digital game not a physical toy
yeah you'd need to make the rooms and have anchor points on each part of the wall
Well @rich adder how would you suggest I get on the path to build that type of game what kind of basics should I know
start with the basics !learn here
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
the pathways gets you going learning basics like positions, transforms and other components important to code what you want
Fair do you remember that toy @rich adder by chance
i was zombified by gameboy at the time lol
@rich adder that is another thing I was thinking about doing but I’m not sure if it envolves unity to try and put emulated games on my gameboy sp
but yeah does look like it uses some type of magnets/connectors to link the cubes
not even worth the effort tbh
Really the games are so expensive now
@rich adder would you possibly be willing to help me
With the game once I learn some stuff
Eh I have too many projects already committed to
you can try in !collab
:loudspeaker: Collaborating and Job Posting
We do not accept job or collab posts on Discord.
Please, use Discussions to promote yourself as job-seeking, advertise commercial job offers, or look for non-commercial projects to participate in:
• Collaboration & Jobs
Fair that makes sense I honestly am hoping I can get this done I know I can make all the animation for it I just gotta figure out how to run it in a game
well thats what learning the tool is for 🙂
Ok, found a good method. It's to set the panel as the current selected object. Then implement ISelect/DeselectHandler.
Yep hahah I can’t even get the editor to install now
It’s doing this then failing to validate? @rich adder
wait longer n make sure you pressed Yes when prompted by PC permissions.
also this isn't code question
Ok I’m sorry
hello, is there a way to instantiate an object directly from the assets instead of making a prefab and assigning that as a variable?
Either use Resources or Addressables
how do i do that?
Google it
Well what did you try? What did not work? How does your code look like?
hold on
nevermind
it was my ide
allgood 👍
thanks anyways
i have another issue now..
when casting my ray, its returning the position of the object it hit
Which sounds like the whole purpose of casting a ray
yeah but like, im casting a ray at a large plane, it hits, then returns the position of the plane its self. I wanna know the position of where the ray hit\
ty
Google is your friend with this
Hello. I want to be able to send data between one object (the truck) to another (the drop off location or the crate). How would I go about doing that through scripts?
Data may be like on the lines of "Hey, you've gained one crate" or "Hey you have been picked up"
Get a reference to the other script and call a method on it.
The basics of the basics
Is there a tutorial on this?
Plenty.
I'd recommend going through 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!
As they cover this and many other basics that you need to know to get started.
Hmm okay. I have been following the junior course, maybe I missed a step or forgotten something
You'll get there :) Starting out with Unity there's so much ground to cover and it definitely takes a while for it all to sink in.
If you don't know how to reference objects/components, you've definitely missed something
https://learn.unity.com/tutorial/lab-1-personal-project-plan?uv=2022.3&projectId=5caccdfbedbc2a3cef0efe63 Following this course, I am on Lab 1, trying to make this mini game. I don't feel like I covered referencing in the Lesson 1.1 to 1.4 with their car and plane thingy. It was mostly collision boxes
Overview: In this first ever Lab session, you will begin the preliminary work required to successfully create a personal project in this course. First, you’ll learn what a personal project is, what the goals for it are, and what the potential limitations are. Then you will take the time to come up with an idea and outline it in detail in your D...
Yeah, reviewing it, Unit 1 does not cover referencing
If the solution is to stop this mini-project, continue the course to learn more, and then come back to it, I guess I should do that
That is, I fear, the way to do it
Alright then. I will do that. Thanks.
But playing around on your own in-between the courses to figure out where you are on your learning path is definitely a good idea
The thing is the "I don't know what I don't know" that is kicking my butt
Like earlier, I found out through asking here about wheel colliders.
I will have a better look at the course syllabus overview, maybe that will guide me better.
I think you're just supposed to follow it as is, without trying to implement new features. The junior programmer pathway probably covers more code related stuff, including references.
The essentials are more to teach you to work with the editor if I understand correctly.
I see! The lab work looked to me as if it's a "Go off an do a thing". I did try that not realising that I should have kept within the parameters of what was taught.
Maybe within the extents of what they have covered in the course.
The final goal is that you would know where(in the manual/API docs) and what to look for when you need to learn about a feature or implement one.
Thanks again! I will do the tutorials. It appears that Unit 2 and 4 of the Jr. Pathway covers what I need.
Hello! I'm getting a strange visual error that could use some help. I'm using 3d drag and drop but the z position keeps changing during the drag part, it looks like it flickers between 10 and zero. I've tryed to set z to zero but that made it even worse. Is there a problem with this script?
using Unity.VisualScripting;
using UnityEngine;
public class Draggable : MonoBehaviour
{
private Vector3 mousePositionOffset;
[SerializeField] private Camera m_Camera;
[SerializeField] private Vector3 originalPosition;
[SerializeField] private Vector3 draggingPosition;
[SerializeField] private Vector3 finalPosition;
[SerializeField] private bool backAtStart = true;
[SerializeField] private bool dragging = false;
public bool dragable = false;
private float elapsedTime = 0;
private void Awake()
{
m_Camera = FindFirstObjectByType<Camera>();
}
private Vector3 GetMouseWorldPosition()
{
return m_Camera.WorldToScreenPoint(gameObject.transform.position);
}
private void OnMouseDown()
{
if (!backAtStart || !dragable) return;
originalPosition = gameObject.transform.position;
}
private void OnMouseDrag()
{
if (!dragable) return;
dragging = true;
gameObject.transform.position = m_Camera.ScreenToWorldPoint(Input.mousePosition - GetMouseWorldPosition());
}
private void OnMouseUp()
{
if (!dragable) return;
finalPosition = gameObject.transform.position;
dragging = false;
if (finalPosition != originalPosition)
{
backAtStart = false;
StartCoroutine(ReturnToStart(1f));
}
}
IEnumerator ReturnToStart(float waitTime)
{
while (elapsedTime < waitTime)
{
gameObject.transform.position = Vector3.Lerp(finalPosition, originalPosition, (elapsedTime / waitTime));
elapsedTime += Time.deltaTime;
yield return null;
}
elapsedTime = 0;
backAtStart = true;
transform.position = originalPosition;
yield return null;
}
}```
I'mma go with you'd probably dont want to be dragging the cards in world space
gameObject.transform.position = m_Camera.ScreenToWorldPoint(Input.mousePosition - GetMouseWorldPosition());
Are you zeroing out the z here? That's a bandaid you can do probably
in future please post !code correctly
📃 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.
Thanks for the input! I've tried to play around with the z axis in that line, but it makes it worse. I've tried : cs //gameObject.transform.position = m_Camera.ScreenToWorldPoint(Input.mousePosition - GetMouseWorldPosition()); draggingPosition = m_Camera.ScreenToWorldPoint(Input.mousePosition - GetMouseWorldPosition()); //gameObject.transform.position = new Vector3(draggingPosition.x, draggingPosition.y, originalPosition.z); //gameObject.transform.position = new Vector3(draggingPosition.x, draggingPosition.y, transform.parent.position.z); gameObject.transform.position = new Vector3(draggingPosition.x, draggingPosition.y, -5f);
This isn't 2D, right? Confirm that the drag is what's changing the z
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/RectTransformUtility.ScreenPointToLocalPointInRectangle.html
This is usually the method you want to use when dealing with canvas type dragging because you want to be dragging on a defined plane
Thanks, I'll look into that
assuming you are working with rect transforms
Otherwise you can probably add a transparent quad in the background with a collider to define yourself a plane if this is all in world space. Though, zero-ing the z should work fine so if you can figure out what's causing the issues with it.
How do i reference AudioRandomContainer in code? (no i dont need AudioResource)
Like, scripting API doesnt even have it
This tutorial will guide you through creating and configuring an Audio Random Container in the Unity Editor, a key tool for dynamic audio experiences. You'll discover how to add multiple audio clips to the container and set them up for randomized playback. Additionally, you’ll delve into the various Trigger modes and learn how to manage these au...
!cs
Join the C# Discord server, a programming server aimed at coders discussing everything related to C# (CSharp) and .NET. https://discord.com/invite/csharp
!learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
google learn c#
📃 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.
sorry
also, this might be a #archived-networking question (probably fine here for now. if it gets anymore complex though, definitely post it in #archived-networking)
yeah
so you can't do this?
The error squiggles are cus you forgot break;
missing the break at the end
the way I wanted it is if I get any of the cases, it executes what's inside case 3
I know I don't have breaks
you can however do this safely:
switch(blah)
{
case 1:
case 2:
break;
default:
break;
}
case 1:
case 2:
Debug.Log("I log on 1 AND 2")
break;
fallthrough only happens when there's no code in the case
then add something but you cannot do the fall through anymore
thats sad
if you need more complex checks you just need to go back to if else
I guess I can do this?
if theres no errors, exit the method
if theres any kind of error, log it, and do the last 2 instructions
Except in the previous code you shared those last two lines only happened in case 3
What they wanted to do is have cases 1 and 2 fallthrough to case 3 anyways hence no break in those cases
If the whole point is to log a message and to ensure case 0 is not handled, then just write it in steps rather than introducing a switch
yea that one was wrong
var result = RecalculationConditions();
if (result == 0) return;
var message = result switch
{
1 => "Foo",
2 => "Bar",
_ => "Baz",
};
Debug.Log(message);
agent.destination = ...
I assume Unity has inline switches by now?
no, I wanted to leave if its case 0, and log errors and do something if any other case
See my code example
c# is an object oriented language
did you even check !learn ?
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Even better would be to cache the strings, or put them in an array. Then you can access it from the index of result
In this mission, you’ll refactor the inventory project you completed in the previous mission using the pillars of object-oriented programming as a guide. You’ll deep dive into the inner workings of each pillar individually, so you can better understand its value in developing applications. Next, you’ll learn how to profile your code to identify ...
oh yeah I see
I mean, the way I did it should be fine tho no?
the last one
btw yes this is for pathfinding
thank you
// Somethere at the start of the class.
private static readonly string[] _resultMessages = [
"Foo", "Bar", "Baz"
];
var result = RecalculationConditions();
if (result == 0) return;
Debug.Log(result - 1); // Index starts at 0
agent.destination = ...
Yes it is, these are all tips and performance improvements
tbf I might use this because this logs all errors
Then use the array, otherwise you are constantly making strings
oh
This also depends on how often the code is called though. If it's not frequent, it does not matter
my idea is that I'm generating random points to wander towards
if the distance from the point is too big, or the status is invalid (tho im not even sure that helps) or the character doesnt move for a specific amount of time, I want to recalculate
I'm using Random.insideUnitCircle, which can generate points inside walls or outside the game field
I couldn't find a better way to check if the point that the agent is trying to move towards is actually accessible
wow
Sorry I can't really comment on Unity specific behaviour since I don't actually use Unity
But I am more than happy to help with general C#
im pretty sure you just cant
i think audioRandomContainer is more like a scriptable object
you aren't supposted to change it at runtime
thus is why you dont need access to it
(im probably wrong though, i haven't used it before)
I just need to access list of audio clips, bruh, even scriptable objects are accessable, could have just made them { get; private set }
What are you trying to do
I need to get list of clips at runtime
why not just make a seperate list?
@grand snow ?
In order to do what
Its a unity server so ofc what people ask will be unity related
I preload AudioClip's in loading screen, i have list, but instead of manulaly putting every audio clip in Container , i wanted to use AudioRandomContainer
Not every question in here has to be Unity specific genius
There are also questions that generally revolve around C#
If they're referenced in the container they'll get loaded anyway
Yeah but surely like 99% are gonna be? It just seems like an interesting choice to join a Unity server when you don't use it 😭😭
arent they are loaded when they are played if PreloadAudioData is not set on clip?
Then your question from a few minutes ago would not apply here since you were asking about C# syntax which has nothing to do with Unity
Okay i guess ill just make audio data preload at start
Yes true
Surely you can understand that when you code for Unity, it often revolves around general C# and questions might not involve Unity at all?
i wanted to avoid that
well yeah, finding loopholes is easy like this, just "use common sense" is the answer to this
yeah that's definitely true. still a bit strange, to see someone who doesn't use unity give help in the unity server lol
to be fair the Unity server is 3x more active than the C# one sooo
Yeah, but also there's a whole lot of Unity specific classes and functions and stuff that are oftentimes also involved
Oh that's fair
I'm using IPointerClick, is there a way to have the event continue to propagate up even if one script already catches it?
Luckily 99% of the questions asked here can be Googled
Valid 😭
I think if you call "Reset" on the event?
Nothing strange about it
Or something with the Use and used property?
You come here asking coding questions and the majority often do not involve Unity
I don't see why it matters anyway
I guess it doesn't, anyone here is free to step in to help when they can help (general c# or unity specific)
public abstract class AbstractEventData
{
protected bool m_Used;
public virtual bool used => m_Used;
public virtual void Reset()
{
m_Used = false;
}
public virtual void Use()
{
m_Used = true;
}
}
Ig Reset().
And if I am not experienced with it, I don't help with it
as long as you are aware of other unity specific gotchas and limitations
like how old our c# version is 😭
I think this is kinda obvious but what if you're using Button or Slider? You can't access the EventData of it unless you inherited your own and reimplemented the event handler.
Yes you would do exactly that
It's not old
.NET Standard 2.1 is the latest version and Unity runs on it since 2021.2
no it has the feature set of something around c# 6/7 so its lacking certain features
probably due to the use of mono and not the .net core clr
it's pretty old, we have only a subset of C# 9 features
the current version is 13 already
Hopefully in this year we actually get the promised updates 🙏
Unity 6 allowed file scope namespace even though it's still Standard.
Is there a reason why we can't use newer C# syntax even with older C# versions way before that?
Seems like I can do C#10 syntax in a .NET Standard in a normal project.
I presume because mono or whatever else unity has modified or slapped on
C# 9 apart from a few things like init-only setters and records and stuff
I would not call that old
When it migrates to CoreCLR it probably supports the latest version
Of course we can't really use actual newer C# features like record structs. Whatever actual means.
Also other new standard library functions or optimisations, mostly Linq for the latter i think.
These aren't available even if we made the C# syntax to match newer versions.
I pray hard hoping it's not just locked on one C# version.
As in you can't modify to an older one?
I don't know how strict Unity handles the csproj files, but I would assume you can just modify it?
to be honest, I don't understand the relationship between Mono/CoreCLR, the version of .NET, and the version of C#
Mono is the runtime. .NET is a set of libraries. C# is the language standard.
I think that's the idea?
Oh, yeah that is dumb
Once they do switch to CoreCLR, I also wish they would just allow standard csproj. I feel like the Assembly Definition files are kinda wonky. But I also have a feeling they won't because they would rather keep controlling properties in the Unity editor.
csproj files are super useful
Can Unity make Turn based game? if yes Do you suggestion tutorial pls
Of course it can. If you google this there are plenty of tutorials
thank you.
Why not? It's just a game engine. It's you who makes it turn-based. A simple Google search will yield a plethora of tutorials. Have at it . . .
That has been confirmed to be part of the transition to CoreCLR, integration with MSBuild, which will also allow for using NuGet directly.
What's confirmed? I have two sentences there. 
That they will add MSBuild support, which means support for user managed csproj files.
Ah. 
MSBuild Integration and Convergence
We’re making progress on fully integrating MSBuild between Unity’s internal build pipeline (for UnityEngine modules) and the user code compilation pipeline. This convergence will lead to a more streamlined and optimized workflow.A key benefit of MSBuild integration is an improved IDE experience. In the past, building from the IDE didn’t use the same compilation pipeline as Unity, which could lead to inconsistencies. With MSBuild integration, we’ll share the same pipeline, ensuring the IDE build process is reliable.
MSBuild will also bring a major upgrade by standardizing the C# compilation pipeline, including support for NuGet packages. Another advantage is the extensibility of MSBuild, allowing developers to customize the managed code build process more easily.
https://discussions.unity.com/t/coreclr-and-net-modernization-unite-2024/1519272
Exciting!
Btw, how can you copy parent component values and paste it on an inheriting component?
The option's grayed out.
You would think that it's possible but apparently not 🤔
I bet you could just rewrite the copied data to pretend it's from the child component type
but I forget how to actually edit the copied component (you can't paste it externally and when copy it back in, annoyingly)
Found out that Awake does not guarantee to be the first event called across all game objects.
It's mixed with OnEnabled.
That sounds strange to me. Where did you read this?
i was about to say same
Maybe they mean 2 gameobjects in the scene are not guaranteed to have the calls invoked in unison?
eg Awake-> OnEnable might be called for gameobject 1 before Awake->OnEnable is called for gameobject 2
Awake is always called before OnEnable on each script, but for an entire scene, it gets initialized as:
object1.Awake
object1.OnEnable
object2.Awake
object2.OnEnable
Instead of:
object1.Awake
object2.Awake
object1.OnEnable
object2.OnEnable.
OnEnable happens when the instance of the MonoBehaviour is created, which is just after Awake
You might be confused with how Unity handles the lifecycle when it first loads a scene vs when you add concurrent gameobjects @static cedar
Really? Does it do all of those and then Start for everything that’s enabled?
Start is called just before the first Update of each script.
Right I’m aware
But I mean in terms of entire scene execution
I always thought it was:
All monos - Awake
All monos - OnEnable
All monos - Start
Of course it needs to iterate through each one during each phase so getting references to things all in awake isn’t going to work often
Which is why sometimes its better to do it in start
Because for sure what happens is any Start will occur after all Awakes
Awake and OnEnable run on each object in the scene on frame 0.
Start then runs on every object on frame 1.
The entire execution with Start and Update would be ordered like this:
Scene load:
object1.Awake
object1.OnEnable
object2.Awake
object2.OnEnable
First Update
object1.Start
object2.Start
object1.Update
object2.Update
Subsequent updates
object1.Update
object2.Update
Okay interesting. I never knew this
They run together (as they always do, given that the behaviour is enabled)
Also, every Start method on a certain frame runs before every Update method on the same frame
Hello, I'm looking for help with a script that I've tried in multiple projects and scenes, but it still behaves the same way. The issue is that some seemingly random value is thrown into my drag value making the dragged object appear ofscreen half the time. it also makes the movement appear to move at half the speed of the mouse. Please take a look at this script in one of your scenes and help me find what is wrong.
https://paste.mod.gg/duygzyexnuoo/0
A tool for sharing your source code with the world!
This is probably right, I wrote it wrong.
I was not sure about that, so I had to go and test it!
smells like two things are fighting over the position of the card..
I've tryed it in an empty scene, which made me think that not the case
GetMouseWorldPosition is named wrongly. It should be GetCardScreenPosition
Since we're talking about Awake and OnEnable, I feel like I should mention again the secret event methods that happen even before Awake and OnEnable...
void __internalAwake();
void OnEnableINTERNAL();
void OnDisableINTERNAL();
https://github.com/Developer-Notes-Extension/Unity-Notes/discussions/288#discussioncomment-5748519
Given how the card looks like it's flying out of the camera, I think the card is getting moved on the Z axis
Do you have a perspective camera?
Even if it's orthographic, this part is very suspicious:
gameObject.transform.position = m_Camera.ScreenToWorldPoint(Input.mousePosition - GetMouseWorldPosition());
ScreenToWorldPoint needs a Z position to know how far from the camera the point should be
for keeping movement on a plane i use screen point to ray and then i use a Plane cast
Oh yeah, that's exactly the problem
And that's exactly the fix (:
Input.mousePosition - GetCardScreenPosition() will have a negative Z component, assuming the card started in front of the camera
Plane dragPlane; //Your plane
public void OnDrag(PointerEventData eventData)
{
var dragPosRay = eventData.pressEventCamera.ScreenPointToRay(eventData.position);
if (dragPlane.Raycast(dragPosRay, out float hitDistance))
{
Vector3 newPosition = dragPosRay.origin + (dragPosRay.direction * hitDistance);
transform.position = newPosition;
}
}
an example via the event system
Therefore, ScreenToWorldPoint will give you a point behind the camera
It'll flip-flop back and forth every single frame
(also, Plane is straightforward to create -- you give it a point the plane should go through and the normal vector, which is the direction the plane is facing)
So you'd make a plane that:
- Goes through the original position of the card
- Faces the camera
Thanks for the advice, I'll get right on that plane
is this the right way to go about this, it seems very dumb (the code is in a state machine so i cant make the gameobjects public) ```csharp
private GameObject playerPrefab;
private GameObject enemyPrefab;
private Transform playerBattleStation;
private Transform enemyBattleStation;
private TextMeshProUGUI playerName;
private TextMeshProUGUI enemyName;
private Unit playerUnit;
private Unit enemyUnit;
public override void EnterState(BattleStateManager battle)
{
playerPrefab = battle.GetComponent<BattleStateManager>().playerPrefab;
enemyPrefab = battle.GetComponent<BattleStateManager>().enemyPrefab;
playerBattleStation = battle.GetComponent<BattleStateManager>().playerBattleStation;
enemyBattleStation = battle.GetComponent<BattleStateManager>().enemyBattleStation;
playerName = battle.GetComponent<BattleStateManager>().playerName;
enemyName = battle.GetComponent<BattleStateManager>().enemyName;
SetupBattle();
Debug.Log("Initializing battle");
}```
You can reference prefabs by a component type
I almost never reference prefabs as GameObjects
also, you already have a BattleStateManager
i think its part of internal systems, like serialization system and it shouldn't be touched

