#π»βcode-beginner
1 messages Β· Page 510 of 1
+= is fine, it's the multiple inline assignments that makes my skin crawl
Never had a use for it anyway
ok, so how would you set 3 variables to the same value?
Yeah, it applies to all of them either way
Well, either you do a single instruction per variable, or you use what I wrote earlier
I have no problem with a = b = c = 1; Makes perfect sense to me
To avoid an unneeded discussion, let me just say that the average person would have to spend a significant amount of time figuring out what a line like that would do. That would be enough reason to advice against it tbh
I don't have any issues with that either personally
And it might have been a mandatory thing in C or C++, but this is a C# server
If that is your argument then they are seriously lacking in education
I'm the kind of person to do
int fd
if ((fd = open(...)) != -1) {}
That's just a pathway, I understand and agree that code must be readable for the vast majority of people, that's why commenting is something to do
but that is C, not C#, so I can understand that not being the norm here
Sorry, maybe I'm a bit quick to judge, but it has only been a few days since somebody here suggested the use of a nullable boolean because it's good to have a "maybe" state π
That's standard C yes
If you have to go out of your way to figure out why something like it exists (in this case it would be relevant for both) then it's time to rewrite
That's sort of how I used to work in lua lol, just set a var to nil, problem is that when you verify the value of the nullable boolean, you can't do if (!var) as this would be true for both null & false
me thinks you don't know about the fundamentals of computing, the transistor, upon which all things digital is built, is a 3 way switch. I could simulate the world using nothing but a bool?
You think the average programmer would care?
no, but they should
Of course not
If you would care so much about this then you would not write with C# to begin with
wrong, you use the tools which are available to you in the context of which you are working
Let's at least learn the beginners the proper way to manage states then π
how about we just educate them to think, that would be a damn good start
im instantiating in a card in script and then in its awake function im creasing the alpha from 0 to 255 howver once the alpha gets to full the cubes start to blend together (the cards are two small cuboids stuck to the back of eacother
with different materials on different sides
That doesn't sound related to any code
And even if it did, you didn't share any
Do that, and maybe a video
All I can say is that it sounds like z-fighting
So what's the question/concern?
Is there a cell count limit for unity's built-in "Grid" component? Like 10 rows and 15 columns or something like this?
If I had to guess, probably 2,147,483,647
Just the limits of int yeah
of course actually havoing data in that many cells will be a memory limitation on your system overall
Hi, i'm new in C# so sorry if i'm asking something simple, the program tells me the next error:
Idk how to fix it, someone can tell me what i have to change on the code?
start by getting your !IDE configured π
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
aight
looks like you just misspelled "position" on the line where you are setting highestPoint
a configured IDE would show them that too, which is why it is a requirement to ensure it is configured before providing help
What is postiion
opsπ€ , damn and ihave checked it like 5 times
next time try !ask ing a proper question
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #πβfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
It did answer your question
trueeee
i mean dont gotta be a jerk about it but ok
you can do ! asking instead of ! ask ing, plural pronunciations work for the bot which is nice (this is not a jab or anything just to be clear)
I can't seem to find a way to get all the scenes in my project that aren't loaded, and from there get their names.
From what I understand, I only have the option of fully loading a scene with a specific index to check what the name of it is.
If this scene doesn't exist, then it just doesn't load.
SceneManager.sceneCountInBuildSettings gets the amount of scenes in the build, which is 3 for me.
I then attempt:
for (int i = 0; i < SceneManager.sceneCountInBuildSettings; i++)
{
//(doesn't work) Scene s = SceneManager.GetSceneAt(i);
//(doesn't work) Scene s = SceneManager.GetSceneByName(name);
Scene s = SceneManager.GetSceneByBuildIndex(i); //doesn't work
if (!s.IsValid()) continue;
if (s.name.Equals(name, StringComparison.OrdinalIgnoreCase))
{
return s;
}
}
This, however, tells me that I don't have a scene at index 1 because it isn't loaded.
I need some way of "peeking" at a scene, like in a list without having to pop the damn thing.
it finds the first scene in the index, because that's the currently loaded scene. The rest are invalid with an index of -1. It's not a valid scene, even though I know there are scenes at index 2 and 3.
The rest of those functions (SceneManager.GetSceneXXX) only work with scenes that are currently loaded.
This is the kind of thing that a lot of games end up building some custom tooling around, i.e. with ScriptableObjects and some pre-build scanning editor script.
How can i assign controller 1 too player 1 and controller 2 too player 2? Because righnt now both controllers controll the same player
huh... that feels almost like a limitation. Any plans on fixing this for Unity 6?
I haven't really bumped into this issue until now - but it does feel like a glaring one.
Not that I'm aware of
It feels like a limitation because it is one
Unity doesn't have a way to read "metadata" from a scene before loading the scene
that's a big subject. There's lots of videos and blogs about how to set this up properly, none of which someone can comprehensively write in a single message here.
If you use the new input system, PlayerInputManager/PlayerInput handle most of this automatically for you.
ok thanks
Thanks
@wintry quarry so, what do I do then? I need to load all scenes in the background and store their names based on index...?
no metadata available AT ALL?
As mentioned, build your own system e.g. with ScriptableObjects
is there a more efficient/common way to see if two Vectors are nearly equal, or is this fine?
private bool PositionsAreEqual(Vector3 pos1, Vector3 pos2, float tolerance = 0.1f)
{
return Vector3.Distance(pos1, pos2) <= tolerance;
}
The == operator checks for "near equality" as well, but without the ability to tune the tolerance https://docs.unity3d.com/ScriptReference/Vector3-operator_eq.html
(hardcoded at 1e-5)
π€¦ββοΈ cool deal, thanks. i made the bad assumption there was no tolerance. i really have to get better at checking docs. also, considering how float works, i should not have made that assumption in the first place.
well, that was an adventure! With my extended programmer (i hate to say it, but it is ChatGPT 4o and 4o-mini). i now have two scripts that together do the following:
Place a Nav Mesh Obstacle where any Terrain Tree is, since there is a bug in the system that does not add a tree as an Obstacle in the Nav Mesh Surface. https://issuetracker.unity3d.com/issues/navmeshsurface-trees-placed-on-terrain-are-not-taken-into-account-when-baking-navmesh (thanks @steep rose finding that, and stopping me from wasting more time). this allowed NPC/AI/Player to walk through trees, or to get Nav glitched on them if you use Tree Colliders, which i consider absurd. Automatically swap to a Prefab version of the Tree when close, and back to Terrain Tree when you walk away. i use the same Prefab to make the Terrain Brush since it strips everything except basically the Mesh/Mesh Renderer anyways. this allow an auto swap to the correct prefab without having to manually cross reference which Prefab should replace which trees. The common rotation and scale issues are resolved and match perfectly when swapped back and forth between Prefab and Terrain Tree (Thanks @robust schooner for a vital piece of information about that).
The Nav Mesh Obstacle is Destroyed and the Nav Mesh hole/Carve is removed automatically when the Tree is chopped down/Destroyed/is temporarily in Prefab form. i may change it a bit to keep the Obstacle in Prefab form, and remove only if either Terrain Tree, or Prefab is Destroyed.
How to reproduce: 1. Open the attached project (TreeTest.zip) 2. Open scene Scenes/SampleScene 3. In the Hierarchy window, double-cl...
BTW, ChatGPT released a tool called Canvas today (for paid accounts. goes free and teams soon)
I made a script called game manger but the icon won't show up, not sure what I'm doing wrong when I'm following a tutorial.
it does not show up anymore, by Unity design choice/bug fix. it is not a problem @whole gyro
haha sorry for finding that, I know it bummed you out but it is what it is. also I wouldn't rely on gpt as a second programmer, you know my stance already π
ok I wasn't sure how to make the gear sign show up but thank you
to me, ChatGPT as a learning from scratch tool for coding is a bad idea. however, if you know enough to comprehend the(often) bad code it gives you, and prompt it to fix it, it is just a tool like any other in my arsenal. It writes working code for me faster than i can myself π
yw. so there is not a misunderstanding, it does not show up automatically any more, intentionally. it did used to. you may be able to manually change the icon of that script, i forget if you can or not. you can also use free iirc assets to change icons
Learning c+ by making pong so stuck on what to place in the script for keeping of point. A nice way to ease myself into c+
you mean c# right? c and c++ are both different languages, c+ isnt a thing
All programmers use AI to understand code now days
https://learn.microsoft.com/en-us/dotnet/csharp/
microsoft has a good learning site for pure c#. theres also the unity !learn for unity related stuff
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
mb
No programmer uses AI that way, wannabe programmers try to use AI to think that they know how to code, but dont know anything
as usual the answer is somewhere in between.
Catch up to the time before you're left behind AI makes us faster programmers
np, was just confirming so i could send you the links above.
If you know how to code, then AI is a great assistant to code faster (AI autocompletion), but code generation like as to understand code (chatgpt) is like wrong
But you need to know how to code, to catch the AI completion hallucinating
to me gpt isnt as useful as just looking on google, also you could probably release the code to help people that have that problem if you want
Also reminder of the rules, we do not allow AI code as answers here and will not help with AI Garbage Code
Same for most actual programmers, most likely :). Yeah, i will be releasing the code on GitHub soon. i have to write up instructions
I would say copilot or Jetbrains AI Toolbox is a way better assistent in those cases then generic chagpt prompts
Where do yall sell scripts
we dont
the Asset Store
the hardest part is getting beginners to understand this. they ask AI to make a for loop then are forever convinced it works for every aspect of their game.
If its useful, yes we do on the Asset Store
Didn't use AI to learn sql won't use it to learn c#
Good choice, it cant teach anything
I know you can buy assets on the asset store, but usually they dont just contain raw scripts only
you can just go on github and probably find something for free even
there is plenty of scripts on the asset store, look at networking stuff or other stuff, its all just scripts
If you use the reverseFlow method for splines, make sure your splines aren't broken; otherwise (comparison between mirrored and broken splines), otherwise the splines go crazy.
I'm having a problem finding where to set the free Look default center to. it keeps on reseting the cam just below the waist and I want to raise that a bit. any idea how?
I dont know whats happening but im trying to make my capsule go up hills smoothly and not slow down but it does the opposite. Its slows down heavily https://pastebin.com/6qG3geG8
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.
My visual studio I dont think is synced with my unity project cause it says "Miscellaneous files" I checked and visual studio editor is installed in the package manager and the external tools script editor is set to visual studio, anyone know why this is? Mb if this is the wrong channel btw
If your IDE isn't providing autocomplete suggestions or underlining errors in red, then it needs to be configured.
the workload is installed & fully updated however it still doesnt like me
And you've tried the
If you are experiencing issues
Section's steps?
ye
Assuming you did everything correctly and it still doesn't work, try regenerating project files.
!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
Kind of a simple question, but how can i get the parent object of a child object, specifically so i can destroy the parent? The only thing i can figure out how to do is to get the transform, which cannot be destroyed
https://docs.unity3d.com/ScriptReference/Transform-parent.html
then you would get the .gameObject if you want to destroy the whole object.
Thanks!
Hmm i have a question, if i want a panel in canvas to fit the text , but also have panel size limit, how should i do it properly?
My character is currently standing on a rotating wheel but the problem is that its not dragging my character with it when my character stands on it
any solution?
hi so I need help with something I am trying to export anim files to fbx but everytime it's imported in blender the animation doesn't play and is wrong and is not attached on the model am I doing something wrong?
did you code anything so that it'd move along with the platform in the first place? this isnt the default behaviour of anything
this is a code channel
how do i do that
oh sorry, where can I ask?
the first thing id start with is detecting when objects are on the moving platform, then applying the same movement that the platform does to those objects. many tutorials will show you just parenting the object under the platform, which is really not ideal in a ton of cases
Which ide is best for unity, im using vs code right now
whatever you like best
i use the visual studio
Visual studio or Rider
Visual Studio works best but just for Windows (or Mac, but I believe it's discontinued)
Rider also works best, is cross platform, but requires payment
There's the EAP for Rider which means you could get it for free, assuming you read the license
VSCode also work but it has always had bas support. However, I believe it is better nowadays so it might also be a good option now (haven't checked)
Also next time, use the proper channel pls
Which one
On second thought, this channel is probably also fine. People usually post code questions about actual code, not working with code
I have been trying to get my save and load game to work for an inventory system script I wrote but nothing seems to save the items in my hotbar or inventory. I've tried everything. If anyone got a spare sec I would really appreciate a second opinion hahahah
post your !code. Please use a paste site
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
If you share your code there are plenty of people who can help you in here.
I gotchu
Hello. I have little problem with unity. When I write for example System.IO, I don't see options in visual studio. Where can be problem? π¬ Same with other classes etc
Sounds like your !ide is not configured
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
Save Game Script:
https://hastebin.com/share/uvicobixay.java
Load Game Script:
https://hastebin.com/share/eciladuvop.csharp
GameData Script:
https://hastebin.com/share/jumukihoku.csharp
Item Script:
https://hastebin.com/share/owufaxiceg.csharp
Inventory Script:
https://hastebin.com/share/fujenoridi.csharp
Thanks to anyone wanting to help β€οΈ
Ok I will try it. I downloaded it with Unity. I hope it doesn't miss anything
Seriously, nobody is going to read all of this
All u need is the inventory system and load system I think
Basically I load my SampleScene from my Main scene and I save the game in the SampleScene. When I try to load my samplescene from my mainscene with my loaded data everything is setup nicely except for my inventory π¦ It just doesnt save
What you should do is retrace the steps up until the saving, and see where it goes wrong
See if the data is passed into the part that saves, see if the savng happends, then see if the data is saved
When that's done, do the same but in reverse for the loading
Retrace your steps until you find out where it breaks
Ye I know my guy, I've been doing that for a couple of days. The debug log shows that the item is saved, in the right index, etc. So I am kind of at a loss
This issue right here is very easy to debug when you use breakpoints: https://unity.huh.how/debugging/debugger
Then do the same, but with loading
Set a breakpoint, follow the steps the code does
See if data comes in, see if it's valid, see if it gets passed down to the relevant dependencies that need it
The debugger allows you to view the contents of variables
With all due respect, the time it takes to do this will be shorter than what it takes for anybody here to read the hundreds of lines you shared
Once you know what specifically goes wrong, you can share that part of the code in here in case you don't know the reason
No I totally get it man I am just new to this I am already very gratefull for you taking the time for this π
NP
can anyone help me? I have a rotating obstacle in my game but the player doesnt get affected when it stands on it
you are going to need to give much more information than that if you expect help
hey i need help
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #πβfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
{
var slash = Instantiate(slashPrefab, bulletSpawnPoint.position,Quaternion.Euler(-90f, 0f, 0f));
slash.transform.Rotate(-90f,0f,bulletSpawnPoint.transform.rotation.z,0f);
slash.GetComponent<Rigidbody>();
cooldownAttack = cooldownNormal;
}```
can anyone figure out why my rotations are messed up
the z axis just won't work
bulletSpawnPoint.transform.rotation.z
transform.rotation is a Quaternion which is notably not in degrees. also what overload of Transform.Rotate takes 4 floats?
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #πβfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
you're meant to read the bot message not parrot the command
lol sorry
Alright thanks
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PipeSpawnerScript : MonoBehaviour
{
public GameObject Pipe;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Instantiate(Pipe, transform.position, transform.rotation);
}
}
just help me ;-;
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
and also you haven't actually asked a question yet
You still haven't explained the issue
its an error i need to fix its the UnassignedReferenceException: The variable Pipe of PipeSpawnerScript has not been assigned.
looks good to me! This script efficiently spawns a new Pipe every frame, on the exact same position
So assign it
then you probably need to assign the variable Pipe of PipeSpawnerScript in the inspector
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
but not the one in the scene
Then you have a different instance which throws the exception
send pic of the full inspector
no that's not the correct place to assign
You can add a Debug.Log into the Start method and log itself. Then you click on the log to find the game object: https://unity.huh.how/debugging/logging/how-to#the-context-parameter
also, can't tell if you're trolling
IM NOT ONG
My guess is that it logs twice, and then you will find the wrong one
And stop sending spam, just do it
you need to select the object that has the PipeSpawnerScript Component, then assign the Pipe field there
I mean....
So context: I changed the z internally with a script code yet the object won't move rotations at all when spawning
This is the code that changes the rotation internally
Don't read the individual components of a Quaternion. xyz and w are for advanced use cases only.
also crediting a pinterest account for being the artist of your pfp is crazy
Not a code question and also wtf just cut it out yourself
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PipeSpawnerScript : MonoBehaviour
{
public GameObject pipe;
public float spawnRate = 2;
private float timer = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (timer < spawnRate)
{
timer = timer + Time.deltaTime;
} else
{
Instantiate(pipe, transform.position, transform.rotation);
}
}
}
the piller keeps spawning although i added a timer. why is this happening?
read the code, what would you expect to happen once it's Instantiated once?
idk spawn another pillar ig (lol im dumb)
also POST CODE CORRECTLY, you have been told before
Oh boy, executing that code looks like fun, creating a pipe once per frame π
you need to reset the timer π
I suggest you start learning C# first before diving into Unity
Because your question doesn't even belong here. It's below beginner level
im trying to make a script that enables fog when my vr player walks into it, it doesnt work. why?
using UnityEngine;
public class FogTrigger : MonoBehaviour
{
public bool enableFog = true;
public Color fogColor = Color.black;
public float fogDensity = 1f;
private void OnTriggerEnter(Collider other)
{
if (other.CompareTag("Player"))
{
RenderSettings.fog = enableFog; // Enable fog
RenderSettings.fogColor = fogColor; // Set fog color
RenderSettings.fogDensity = fogDensity; // Set fog density
}
}
}
Hello,
I want to create a system for attack with a bow and change the value of the power of the bow compared to the time the player stay click on the mouse. But, with I have done, my game crashed so I think I have an infinite loop.
The code :
public void ClickHitWeapon(InputAction.CallbackContext context)
{
isRightClickHeld = context.ReadValueAsButton();
Debug.Log("Click hit weapon");
if (isCooldown) return;
if (isRightClickHeld)
{
ArrowTimer();
isCooldown = true;
StartCoroutine(AttackDelay());
}
}
private IEnumerator AttackDelay()
{
yield return new WaitForSeconds(currentWeapon.attackDelay);
isCooldown = false;
}
#region Arrow System
public void ArrowTimer()
{
while(isRightClickHeld)
{
timeRightClickHeld += Time.deltaTime;
}
ThrowArrow();
timeRightClickHeld = 0;
}
public void ThrowArrow()
{
#if UNITY_EDITOR
Debug.Log("Throw Arrow");
#endif
Vector3 position = SingletonManager.instance.playerTransform.position;
position.x += offsetX * playerMovement.orientation;
//If orientaion = 1, do nothing, else rotate the arrow of 180Β°
Quaternion arrowRotation = playerMovement.orientation == 1 ? Quaternion.identity : Quaternion.Euler(0, 180, 0);
GameObject arrowGameObject = Instantiate(arrowPrefab, position, arrowRotation);
arrowGameObject.GetComponent<ArrowCollider>().movementSpeedX = movementSpeedArrow;
}
#endregion
I precise that my input system that call ClickHitWeapon() is in pass through button
yep, infinite loop right here
while(isRightClickHeld)
{
timeRightClickHeld += Time.deltaTime;
}
Why is it an infinte loop ? If i released my mouse, the variable isRightClickHeld becomes false
If your app hangs then it's likely always an infinite loop. It is either recursion (which doesn't apply here), or a bad while loop. You only have one while loop
It runs, then it runs again, infinitely on the same frame
It doesn't end
You need to ensure it checks each frame
Add yield return null; inside the while loop
lol, NOTHING else runs when the loop is active
Right why don't you use coroutine like you did in cooldown
C# / Unity uses threads and you are hogging the main thread with a while loop that runs infinitely on a single frame
So either you add that yield line and check once per frame, or you run it in a background thread (which is a bad solution here!)
Actually, this is wrong
Your method is not even a Coroutine
Oh, I thinking the rest still working while I was in the loop. But that make sense
Because I want to wait depends on the time the player stay clicked on the mouse and not a fix time
There's a lot wrong with this code
Make the method a Coroutine, add the yield
Then you want to call StartCoroutine for the method in ClickHitWeapon
or read the button INSIDE the while loop
Lastly, assuming you want to trigger the cooldown after, add isCooldown = true; and StartCoroutine(AttackDelay()); at the end of the method, or have another coroutine call ArrowTimer and wait until it is finished, and then call those
Regardless, your current code is not going to do what you want at all
Idk why is this a problem
How can I do this in an extern function because I don't have the context variable of the input ?
You don't have to always yield WaitForSeconds, you can return null until button gets released
why do we write List<ClassName>() waypoint = new List<ClassName>(); in unity
While I wrote the code like this: List<ClassName>() waypoint; and it still works fine for me.
When I use the data in it and also it is [SerializeField]
Unity will initialize the list for you if its serialized to the inspector. In the first example, you initialized it yourself.
Also you dont need to type the Type again,
= new(); will be fine there
What does intializing do?
new List<ClassName>(); will initializes the list. when you use [SerializeField] on a private field, it will displays it from the inspector. though, in order to display the list from the inspector, Unity must initialize the list for you . . .
Basically creates the actual object (the list) for you to use. If you have a private list and do not initialize it, trying to use it will result in an error
it will instantiate (construct) the actual object, which, in your case, is the List<ClassName> . . .
So if I make it [SerializeField] then I don't need to write Type = new();
Right!
Why do we need to construct an actual object of it
everything in c# is an object
think of every field as an object that stores data based on its type, and that data is located at a specific address in memory . . .
Oh thank you
If you add field of type List, I guess you need a list, not only the declaration of field that can "hold" that list
Without new'ing it, (or allowing unity to create it by exposing it to inspector), all you have declared is a field which can store that type. No list actually exists yet
Ok gotcha
yep, everything is an object. the key difference is between declaration and initialization; this also depends on if the (object) variable is a reference type or a value type . . .
By the way where I can get the list of reference types and value in unity
yes that is Specific to Unity, you normally should new() it, make a habit being aware of that
the Unity scripting api or !docs (as we call it). all the classes/structs are there . . .
π½
Ok
damn, thought i added the ! . . . π
Yeah, you should decide to [SerializeField] when you actually need that field to be serialized. If you don't, but need initialized list, use new()
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/
everything you need is on the LEFT regarding C# language
eg knowing the differences on how Reference Types and Value types behave is very important
eg. List is a REFERENCE type https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/reference-types
dot?
oh, you mean DOTS?
I should hope not, so early for dots lol
Why cant i invoke my Event here? Im using UnityEngine.Events and it works fine like this on other scripts
what is "Event" ? More likely you want UnityEvent
Yeah sorry I wrote it wrong
that doesn't look like a UnityEvent . . .
also, posting the error message would help . . .
its probably this
https://docs.unity3d.com/ScriptReference/Event.html
no definition defined invoke bla blah
Dots yes
data oriented stack is pretty diffcult if you're new, but any resources can be found on the unity docs/manual and learn site
!learn should have tutorials on how to get started . . .
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
That was it, thank you!
turbo makes games also has good tutorials on DOTS
So what should I watch first
why do you want to write DOTS so badly lol
the tutorials they have. you need to go to the website and look . . .
are you having performance issues?
Imho dots are good start instead of monobehaviors, BUT you NEED to know a C# better
Ok
eh this is #π»βcode-beginner
If you prefer to learn unity along with c#, start with normal OOP
Nope I just like how it optimize anything by more than 200 times
Ok
I mean you can use it, I just wouldn't recommend it until you learn more coding
there is a lot of different concepts that are not regular to oop
Yes ik, I'm jus saying that in my opinion a beginner (of unity) but intermediate in C# can bypass monobehaviors and start learning DOTS
yes its very good for performance, but writing the code is very boilerplate in the beginning and annoying. Not the best for beginner
Was thinking more about not getting narrowed mindset by mono:p
I struggle with this a bit now
imo, at the end of the day you're making a game so yes performance is important but if it hampers progress then its not worth the time unless you really having performance issues that traditional means do not solve
That's right. But if it is only about learning unity, eventually you end up using mb anyways, but can start learning in different order
true, i just see it as you gotta learn the "wrong way" first to see the major benefits in the "correct way"
I wouldn't even worry about DOTS until you know why you need it imho
I have games with "thousands" of instances of items for mobile and they work just fine.. migrating or doing it in DOTS wouldn't improve performance since we're already fine at 60fps and would greatly increase complexity
"greatly" if you're a Unity beginner, that is
To play devil's advocate - even after reaching your framerate targets, improving performance still:
- Reduces energy usage (reduced battery drain) of your application (which user's might not notice at first but will eventually)
- makes it accessible to even more devices
but noit worth entertaining those goals without concrete targets either
Btw I was mainly referring to ECS when speaking dots, cause dots and mb work together just fine so its not like we choose one or the other luckily unity can use both and we can mix GOs with ECS or just use things like JOBS which are very useful MB or not
Agreed, can't think of advantages of doing "pure dots" for a game. But making a system to handle specific area of that game just to offload CPU, even if not necessary, isn't bad idea imo
I had to make an init scene and put my singletons for data persistence and scene management in it so the data in them would be ready for fetching beforehand. When I start the game from init scene, I load the playable scene additively and set it active. I log the active scene and yes it successfully makes the newly loaded scene active. My problem is that I cannot interact with anything when I'm loading from init scene. And the lighting settings are all messed up. Why is that?
hard to say what first issue is without seeing the setup, and are those objects DDOL?
lighting is probably because of switching scene and you have not baked light data, unity creates that when scene is open but does not bake it.
and also which do you mean when saying
cannot interact with anything
what are you trying to interact with ? what's supposed to happen
I set up interactables in my playable scene that I can interact with. When I start playing from my playable scene it all works fine. I can interact with the objects and such.
Like a fridge. I can open and close its door.
did you check the console for errors?
These are the only errors I'm having
hmm seems like some objects are not being carried over in DDOL unless their parent is already ddol
I also check the layers of my interactables to see if they change or anything but no everything looks fine
why would layers change lol
unless you specifically coded to do so
Nope i did not code anything of sorts.
Maybe changing scene messes something up
thats why I checked
those are the warnings / errors you get in new play scene or just playmode init scene? and which objects you put DDOL that is child of another object
The ones that carry over to my playable scene. They are not child to any other object
ok and no camera?
Camera does not carry over. I have my camera set up in the playable scene
I mean i did not anything about it. Does it usually get carried over?
nah just wondering if you had that on DDOL
see if the interactions script is running and put debugs see whats happening inside when new scene switched
Like when I delete the camera from the init scene. My playable scene camera changes angles and stuff
I'm not sure how one would affect the other
I do not know either
are you saving values n stuff?
Just simple booleans about the game checkpoint.
without knowing more whats going on scripting setup wise , all I can advise is to check if logs run whats happening in the interaction script coming from the init scene.
Wait why the hell is my camera coming with me
There is one camera in init scene.
And there is another in my playable scene?
ah well there you go, you might be raycasting from the wrong camera..
well i would take a guess that DDOL has something to do with it lol
Yeah when I disable the first camera. The interactions and all works now. The question is
I did ask about if it was being brought with DDOL. Check all the ddols you're making
I start my game by playing a timeline in the playable scene. Why does disabling init scene camera changes the angle?
I know. I checked it
Like I only have 2 3 ddols in scene and there is nothing related with camera being carried over
show in script which ones you want to make DDOL
https://hatebin.com/scsbflsjdr ->This is the PersistentSceneManagement
https://hatebin.com/kpgofdqnci -> This GameManager.
https://hatebin.com/ouzvycavjf -> This DataPersistence Manager
These three come with me from init scene
are those the only DontDestroyOnLoad you have in script?
btw looks like you never unloaded your init scene instead
you just made new one active, possibly
Well I cannot unload the init scene. I have to have the game data ready all times. Its like, I start a new scene, new scene checks the data if necessary and loads the game accordingly
If i try loading the data and make my scene act on it, the data does not get loaded immediately leaving with exceptions.
what is even the point of DDOL then..
I mean it may be wrong but thats what I could come up with.
So you're saying they are already in the init scene why carry them over with you. They will already be available
if you dont unload the scene objects don't even get unloaded there is no point in DDOL
Yeah never thought about it damn
DDOL is a scene that just never unloads (between scene changes)
So like they will be loaded at start in init scene and stay there for me to read and write. Makes sense
once they are in DDOL(code) they should be put automatically in DDOL(scene)
so its kind of seamless
Hm okay. So what should I search for about the lighting issue?
just bake the light. Even if you use realtime , you should bake the light data. Just make sure to uncheck any baked lightmap mode if you use realtime
All right. I am also new to the lighting things. I must research. Thanks a lot for your help. You're the best.
if I want enemies and players to have health should I make an interface that they can both inherit? Or is there a better way to approach making a generalized health system without using interfaces?
just use a Health component?
composition rather than inheritance is better here
Ty!
you can steal mine if you want
https://hatebin.com/gftqlowwaq
Tysm!!!
Can I get the length of ReadOnlyArray<>?
wat are you trying to do ?
wouldnt it just give you .Count ext method, cause it implements IEnumerable ?
oh, thx, thats exactly what i needed
I've a problem, why at the start of the game I can adjust the volume but when I start the game and return to the main menu I can't adjust it anymore?
(if the code is needed please tell me)
well yeah, we can only guess without seeing code/setup
presumably some null reference
Alright, so the adjusting volume is just a scroll bar, and when you return to the main menu this is the code
{
if(Input.GetKeyDown(KeyCode.Escape))
{
PlayerPrefs.SetInt("LoadSaved", 1);
PlayerPrefs.SetInt("SavedScene", SceneManager.GetActiveScene().buildIndex);
SceneManager.LoadScene(0);
}
}```
and what does any of that code have to do with the volume?
we dont need to see the scene switching mode lol
I meant that when switching the scenes
we need to see the code that gets Input from the slider and outputs to the audio volume
guessing some reference in scene switch breaks
Well there's no code ig.. I added the music prefab and set the volume in the slider
Is there a better way to do it or smh else?
ideally a persistend audio ddol object + audio manager
this shouldnt break though if you switch scene
unless it cant find Music anymore somehow
if you mean its not saving the same value then see above
That's the problem, I think the problem is with the switching scene code
It's not about save, well when I return to the main menu I cant control and change the volume unless I have to restart the game
If I try adding volume saving will that works?
I found a script on reddit I'll try making that
ok and it doesnt work at all when you switch back ?
Look at the start of the game it works perfectly fine, I can adjust however I want, but when I start the game then return back to the main menu it won't work at all
You can see the video I've sent up
I had my audio muted I'm at work
did you check if you have any errors in console when you switch scene back?
Not really, there's no errors at all
can you show the Music object inspector, when you switch back to that scene
Alright, I'll record a video
!bug
πͺ² To make bug reporting as quickly as possible, we made a bug reporting application for you. When running Unity choose Help->Report a Bug in the menu, or you can access it directly through the executable in the directory where Unity is installed. It will also launch automatically if you experience a crash.
π If your bug report is to do with Documentation, either an error, typo, or omission, you can report it by scrolling to the bottom of the page where you found the issue and click βReport a problem on this pageβ!
π‘If your report is to do with a new feature idea, you can check the Unity Product Roadmaps page to see if your idea has already been planned.
For more complete instructions on how to report bugs, access: https://unity3d.com/unity/qa/bug-reporting
!help
bro i installed unity for the first time and i want to try ot learn it but when i click create project
it says
unable to create project
first of all you're in a code channel. so any general unity questions go in #π»βunity-talk
also you should be more clear and show screenshots and any related information
ok thx
Like this? if you need to know anything else let me know
Ah its in a DDOL
pretty sure the slider is now referencing the first one instead
the slider in the scene has no idea you want the audiosarce thats already playing
Oh yeah I get it now but to be honest idk how to fix lol
this is the audio script if it's needed
{
private static Audio audioinstance;
void Awake()
{
if(audioinstance != null)
{
Destroy(gameObject);
}
else
{
DontDestroyOnLoad(transform.gameObject);
audioinstance = this;
}
}
}```
Hi I'm new to coding and I have some questions first what ways are the best to learn coding second are there easy way to learn it and lastly are is there any beginner friendly project that I can try
btw not very good name for this, you should call it AudioManager. Then put the AudioSource here, now when you switch scenes you can easily access it from the static instance
I can't really get it, I've never made a audio script and this kind of thing before, could you explain more please?
wdym you never made an audio script, why did you write Audio in the class and use a singleton
!learn
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
Hello, quick question: I found this character controller on the internet: https://pastebin.com/RXZ1dXgw. I was wondering, is there any way I can get this code explained to me? Since I don't just want to copy and paste code, I want to partly understand what I'm doing.
you can watch character controller tutorials on youtube (specifically ones that use the CharacterController component, not rigidbodies) and they will explain these things probably
Most that I found only gave you the code in 30 seconds and flipped you off, but I'm sure there are some that explain?
Tried asking chatgpt aswell, it didn't give out bad answers surprisingly
To start with, if you only want to partly understand, you are wasting your time. You should want to fully understand.
If you do, re type the code, line by line and every single thing on every single line that you do not understand look it up in the docs until you do
just look it up on google, dont use chatgpt for things like this as it will most likely lead you astray. I always recommend documentation to learn unity it may be my cup of tea but not yours.
most things can be explained via docs
I learned postgres by documentation, and I love reading docs in my free time anyways. What docs should I look for?
!docs
just why what?
visual studio thinks that i dont have installed newtonsoft library but i has
and how did you install it?
with nuget
right so you didn't bother to read the docs that specifically tell you not to do that
so m
Unity does not support NuGet, because it has the control over your C# project file. When you include a NuGet package, VS writes it to the project file, Unity detects the changes and rebuilds the project file entirely before recompiling. You lose the changes VS made
Hey guys I was wondering if youβd know how to sort this error? I havenβt seen this type of error before
The variable groundCheck of HeroMovement has not been assigned. You probably need to assign the groundCheck variable of the HeroMovement script in the inspector
Where is ground check variable? This is what I can see atm
It is the variable called "groundCheck".
This instance of HeroMovement has it set. You have another HeroMovement without it.
how can i make my capsule not slow down when i walk up slopes and not go extremely fast going down slopes?
my script aint working
rigidbody
ok
theres no gravity in my script
i have drag
ok
where would i add that script
im just tryna add hills
oh
ok
Could I be recommended a good save and load system tutorial
hehe nice. its only 5 minutes and should get you going
thanks!
I was wanting to update my project to Unity 6, but im afraid its going to mess it up as Ive never done this before? if i just open the project with unity 6 will it mess it up even though thats not the orginial version its on?
nothing should mess up, but you should have a backup anyway
use GIT and you should be okay (make commit before the upgrade)
Yeah i have it on GIT so ill just do last commit and try it out then Thanks!
What you mean unity flash screen?
Im still on 2022.38f1 lmao
haha, did i hear somene say Unity6 is the most stable and performant version of Unity?
in what bubble?
The standard practice here is to do a test run by copying your project folder to a separate location and opening that in Unity 6 to see what happens. Once you're satisfied, you can do that again with your original project folder.
That said, I've seen that projects are generally holding up quite well with the update with very little to no breakage.
beat me to it
My own (admittedly small) projects converted without any issues.
Marketting Hype
thats good but wouldnt make such a broad claim
id def recommend 2022 for stable
but not having a splash screen is a +
that said.. i am in the process of porting over some of my projects to 6.. but i dont expect it to go 100% smoothly ofc
That wasn't a "yes this will work" broad statement, but sure. Of course YMMV.
ya, thats teh best route u can take tho.. duplicate ur project open it in Unity6 and see for urself
sorry replied to wrong one
i just wanna get rid of the early releases i have
Ah, gotcha
no need for them anymore
i meant to @queen adder
unity 6 is the most stable and performant version of unity and you can set unity flash screen as optional
Thanks for clarifying, I was a bit confused XD
I haven't been able to verify this for myself, but my understanding is that U6 should improve overall performance in some respects, especially with the lighting system?
At least that's the impression I've been given, mostly based on just a few YouTube videos that have talked about it.
ya, i have high hopes for 6.. time will tell
I didn't have many issues during the preview period, so it's what I'm using for my own stuff at the moment. (again, small projects, so that probably doesn't say much)
I have high hopes for whenever they get around to updating the engine from mono to .net core, though... but it'll be a while, unfortunately.
Nyone know why this would be happeneing????
player is getting stuck like theres something blocking it but there isnt anything there and it happens at random.....
How are you moving it?
With the UI BUttons by holding it down and on release you stop
That's not what I'm asking... How does the object move? Via transform? Rb? CharacterController?
RB Character controller
Share the setup and code. Is it a dynamic rb?
Donβt you need subscription to disable it?
not in unity 6
How do you switch to unity 6?
by downloading the unity 6 editor and opening your project with that
You can always switch back right?
better you just make a VC commit/backup beforehand instead though, downgrading is possible just more work/ pain
Figured it out as soon as I left discord lol
Thought it was an update in the actual editor
you might want to save your project first before you go to unity 6, it could introduce a lot of bugs
What kind of bugs? Issues with editor or actual project/mechanics?
you'll know when you get them. it's not the same for every (every project) . . .
I have a 'public Text' variable in my code to display ammo and it works just not with TMP
would anyone know why
put it in a method. you cant use fields inside a function of initializer unless it was constant/static
like awake / start
yeah.... it had a ton lmao, I removed it from installs
Ok let me try that. Thanks!
Random.Range(0, 2); will return 0 or 1 right?
Yes
Hi, I have a Steam Integration cs script in my project that seems to throw up a compiler error only for Android / Webgl when trying to export them. I'm assuming because it's not compatible with those platforms.
Is there a way to have those platforms ignore that script, instead of me having to literally delete the script off my project each time?
yes, wrap the script in an AsmDef then you can mark the asmdev to exclude Android and WebGL
help my tank top is sideways from a follow mouse script
!ask
:thinking: Asking Questions
:mag: Search the internet for your question!
:book: Use the API Scripting Reference and User Manual and this troubleshooting site for commonly posted issues.
:wrench: Attempt to debug your issue.
:thought_balloon: Find an appropriate channel by reading the name and description in #πβfind-a-channel
:grey_question: And don't ask to ask, ask a full question illustrating with screenshots if needed.
-# For more posting guidelines, go to #854851968446365696
There is a lot of things that could be wrong, we can't determine what based on a single image with no code provided
First of all
Its been ages and they still havent updated the Junior Programmer pathway. Is it outdated or still applicable with Unity 6 today?
you mean the one on !learn?
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
Specific class names may have changed here and there but Unity 6 is mostly the same to a junior dev
the deeper you go the more likely it is to find differences π
Yeah
Glad to hear that
Last time I used Unity was when 2021 LTS was released so Im kinda trying to refresh my skills lol
If you want to be sure they have time to update, stay on 2022.3.x for now
its by no means outdated
and knowledge transfers pretty easy
Except the input system
You still have both available
even in unity 6 you have legacy, you can also choose to install the new one in 2022
only the default has changed π
But i would say it even makes sense to take a small sidequest and learn the new input system
When following a tutorial, you're usually best off using the same version of Unity that the tutorial uses - otherwise you will end up wasting your time trying to find the same menu option/ tick box/ bool/ field/ etc
https://unitycodemonkey.com/kitchenchaoscourse.php
This is usually my go-to for tutorials
Unity Learn is too buggy as a website
Unity hasnt changed a lot though, everything is mostly the same. I cant notice a difference between Unity 6 and anything after 2022+
Huh? I never encountered problems
I did, a lot
When I wanted to paste in my WebGL game for example, it gave me a "project_unsupported_url" error
I couldnt complete the pathway
And its very very slow as well
You must be lucky then
because after 2022 is 2023.. and Unity 6 is 2023 renamed.
Most of the tutorials on !learn are pre-2022 ... regardless... what I stated is the best course of action.
:teacher: Unity Learn β
Over 750 hours of free live and on-demand learning content for all levels of experience!
@frank zodiac The same issue loading stops at "Linking build.js(wasm)" for 20 to 25 minutes every-time
Happened to me too
I have tried to change to a "smaller build" and "disk size" in the project setting but I still same problem.
hey i need some help... i have a stickman image, and i have sliced the arms and legs and stuff all separately, and now i want to rig it, but i can only select one slice at a time (in the attched image, i have the torso selected) and when i try to rig it i can make the bones go across to the other slices. ive searched everywhere and idk if im just dumb. ive tried shift and cntrl slecting multiple but i just cant. if you could help that would be great!
pls
Why would you want to select more piece ? You rig each piece individually as far as I can remember.
but i need them to be connected so i can animate the stickman ?
like i need the rig bones to connect to one another
I am trying to make the character jump
But when I press spacebar it plays the jumping animation multiple times
Can anyone help?
which app should i use for learning c#?
@quiet ginkgo Use trigger for jumping instead boolean
app? follow a tutorial on youtube or a blog . . .
can you reccomend me something?
Chrome/Firefox/MsEdge :p MSDN is the best source
i haven't updated this in a while, but these are ones people have used. personally, i learned from the rbwhitaker blog, then followed the unity beginner and intermediate scripting tutorials . . .
#π»βcode-beginner message
also, check the pinned messages. there is a section for beginner tutorials and courses . . .
https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/tutorials/
You can use Microsoft learn thatβs what Iβm doing
I personally recommend learning from documentation, you can learn from tutorials as well but I would use them as a reference since you will get trapped in an endless cycle of using tutorials to do anything.
https://learn.microsoft.com/en-us/dotnet/csharp/tour-of-csharp/
https://docs.unity.com/
public CharacterController CC;
private Vector3 Gravity = new Vector3 (0,-9.82f,0);
private Vector3 Velocity = Vector3.zero;
void UpdateGravity()
{
Velocity += Gravity * Time.deltaTime;
Debug.Log("Is Grounded: " + CC.isGrounded);
if (CC.isGrounded)
{
Velocity = Vector3.zero;
}
else
{
CC.Move(Velocity * Time.deltaTime);
}
}
``` did i do this correctly
tho "is grounded" is switching between false and true. even tho it works
Is there an easy way to build things like walls and buildings without having to keep duplicating objects and aligning them manually?
Probuilder and using the built in snap in unity, alternatively you can use blender as well
guys I have a very specific issue and I can only describe it with images... HOW DO I FIX THIS
as you can see
these 2 give me different characters than they should
yeah thank you but by the time I get a reply there I'll die due to old age
if someone knows they will answer (also did you even post this question in #π²βui-ux? I dont see it anywhere)
have patience
also there are more relavent channels other than code channels as well π€
no, was speaking from experience
thankfully I fixed it just now so yeah nevermind
ask the question and see if it gets answered, but if you already did fix it you don't need to.
Hi, in the beginning of the junior programmer lessons they mention how microsoft visual studio can auto fill suggestions for C#, and show alternatives. I can't figure out how to set this up. Can anyone point me in the right direction?
!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
youre amazing thanks
when working with events, is it common practice to unsubscribe from the event i subscribed to once its no longer used?
lets say i have a falling object called disc, which upon finishing its fall it fires an event "stoppedfalling". everytime i create the disc i should subscribe to the event, and then wait for the event to fire, where i start it by unsubscribing the object from the event since i assume itll never be falling again once its in place
specfically unsubscribing from within the same event
you should sub when the object is active/created and unsub when the object is deactivated/destroyed. this is usually done in OnEnable and OnDisable . . .
private void SpawnedDisc_StoppedFalling()
{
// Detach Event
spawnedDisc.StoppedFalling -= SpawnedDisc_StoppedFalling;
// Code
//
//
}
im a complete beginner, whats on enable and on disable?
is it scopes like start and update?
they are Unity methods. you place the subscribe code inside one method, and the ubsubscribe code in the other method . . .
of the object definition
OnEnable is automatically called when the GameObject is enabled. the same applies to OnDisable (but obviously the opposite) . . .
gotcha, its sorta like the enter and exit dunders of python classes
if you mean a method, then yes. they are Unity methods . . .
ok, another question, what if i cant access or modify the object that im trying to subscribe & unsubscribe?
you mean the falling object?
Either the script creating the falling object or the falling object itself must have a reference to the event they wish to sub/unsub from . . .
yes
thats how i do it right now
what code do you have for subscribing right now?
oh, then you are fine . . .
i have 2 objects i cant access..
an igrid and a idisk
the igrid is spawning the idisk. after its spawned i keep it in a variable and immediately subscribe it. but then when i spawn the next one for some reason the event that is subscribed is fired twice for the one i just subscribed to, and once for the old one i subscribed before. i found the solution by unsubscribing from the inside of the subscribed method after its fired, but i was wondering if it was a good practice
public CharacterController CC;
private Vector3 Gravity = new Vector3 (0,-9.82f,0);
private Vector3 Velocity = Vector3.zero;
void UpdateGravity()
{
Velocity += Gravity * Time.deltaTime;
Debug.Log("Is Grounded: " + CC.isGrounded);
if (CC.isGrounded)
{
Velocity = Vector3.zero;
}
else
{
CC.Move(Velocity * Time.deltaTime);
}
}
```any idea why output is switching between true and false
subscription
...
...
// Spawn Disk & Assign Post-Spawn Logic
spawnedDisc = grid.Spawn(userDisc, col, row);
spawnedDisc.StoppedFalling += SpawnedDisc_StoppedFalling;
...
...
unsubscription
...
...
private void SpawnedDisc_StoppedFalling()
{
// Detach Event
spawnedDisc.StoppedFalling -= SpawnedDisc_StoppedFalling;
// Code
//
//
}
...
...
like that
what/where is output? what is switching back and forth?
!code
π Large Code Blocks
Use links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/, https://paste.myst.rs/, https://hastebin.com/
π Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
this is one way to do it. what happens to the object after it stops falling? does it remain active in the scene, or disappear?
its active and static
it doesnt move until its destroyed when the game is restarted
that part isnt implemented yet
Hello everyone :-),
Im wondering why my player isn't properly rotating towards the mousePosition.
when i attach this script to the player object it creates a weird rotation effect. Its responding to the mouse Movement but it doesnt properly rotate towards the mouse Position. Please Help.
using UnityEngine;
public class PlayerRotation : MonoBehaviour
{
[SerializeField] private float rotationSpeed = 5f;
[SerializeField] private LayerMask groundLayer;
private Camera mainCamera;
private void Awake() {
mainCamera = Camera.main;
}
private void Update() {
RotatePlayer();
}
private void RotatePlayer() {
if(TryGetMousePosition(out Vector3 mousePos)) {
var dir = mousePos - transform.position;
dir.y = 0;
transform.forward = dir;
}
}
private bool TryGetMousePosition(out Vector3 position) {
var ray = mainCamera.ScreenPointToRay(Input.mousePosition);
bool success = Physics.Raycast(ray, out RaycastHit hit, Mathf.Infinity, groundLayer);
position = hit.point;
return success;
}
}
another question, does it matter where i define my variables? i find it most comfortable to define class wide variables for my script. is that bad?
typically, fields (class variables) are defined at the top of the script . . .
Rule of thumb, normalize your directions
this happens when its grounded
tysm
If that doesn't solve it, you may want to add on the player position + direction to localize the direction. I forget
your code only logs the value of CC.isGrounded. we can't determine anything from this. you need to check/show us the code that determines how the player is grounded . . .
its Charactercontroller
it has its own "isGrounded" variable
could you explain what you mean by that idk how to do that with my code
and thank you agaain for the help
what he mean its that, you need to show us or tell us how your "isGrouunded" works.
and specially how you tell / invoke it to another code
Does it make sense though that 95% of the variables i find easiest to be class variables? am i doing something wrong? should i even care?
This will depend on Code Design itself you can check https://refactoring.guru/ for more information.
it can be a collider issue. make sure it's properly setup. are you on a slope? if so, slopeLimit could be the problem as well. is your character just on a flat surface?
Does normalizing it not solve it? Because the code looks fine otherwise to me
you'd only need class variables for those that are tracked/used across multiple methods or reference types. most variables, especially value types, can be local variables . . .
no it somehow doesnt
i notice your event is a public field on spawnedDisc, and spawnedDisc is the instantiated object. are you subscribing to an event on the object itself?
should i send a video of the entire setup? so also how the child and so on are nested and so on?
and also how the beaviour of the mouse influences the rotation of the pllayer with the current code setup?
I'd make sure the position is correct from the raycast, and print out the transform position and direction and make sure those values are correct
sometimes when I'm not sure if the values are lining up I'll stick what I'm working on at the origin such that I know that (0, 0, 1) is forward in both the local and world direction
idk if this will work but, if i were you i think i need to check the dir value != Vector.Zero. then calculate target rotation based on the direction you looking for.
https://docs.unity3d.com/ScriptReference/Quaternion.LookRotation.html
then maybe using RotateForwards after that.
ye its a flat surface
you also have this too:
https://docs.unity3d.com/ScriptReference/Transform.LookAt.html
but setting the forward should work
then i would look at your collider(s) and make sure they're properly sized/setup . . .
what do you mean?
again total beginner π
why is total beginner already doing event subscriptions π₯΅
im subscribing on the instanced object
i tried instancing on the spawnDisc before i assign to it an instance but that didnt work
prolly did something wrong?
why not?
well maybe not a total beginner, just a total beginner with unity
and c# lol
its kinda difficult for a beginner, theres a reason beginner tutorials on youtube never use them
well im familiar with the idea of events, just not how to implement them in unity
i think its the right solution for the use case im trying to implement
but anyway this is for a job interview, its a home assignment so i want to do it with industry standard approach
so its worth putting my time into figuring it out right now
i figured it out. the problem lied in the fact that i was using a render texture on my cam to achieve a pixelated effect but the mousePos wasnt accounting for that
i mean subscription just like Radio, you send the radio then if someone like it it will continue hear the radio talking until it finish.
no, i read the code wrong. it's hard to see when all broken up.
- the instance created is
spawnedDisc - then you access the
StoppedFallingevent fromspawnedDisc SpawnedDisc_StoppedFallingfrom this script is subscribed to theStoppedFallingonspawnedDisc
i thoughtSpawnedDisc_StoppedFallingwas a method from thespawnedDiscinstance . . .
ah no, its another event of the disc that has been spawned inside the subscribed method of ColumnClicked
so basically i gather the information i need for spawning a disc, reach a scenario that requires a spawned disc, then i spawn disc based on an event that is subscribed to the game board which broadcasts the fact and location of what column is clicked.
that results in a spawned object that will communicate when it arrived at its slot
sorry if stupid question, why is the capsule in the ground, what should my center be because i thought it should be half of the height
for starters, the CharacterController is already a capsule collider. this is also not a code question
if pivot is in the center then keep center at 0
ohh right mb i saw beginner and went here, ill ask a diff channel
thanks
hey so im trying to make an object rotate and for now i tried using the script from the unity site https://docs.unity3d.com/ScriptReference/Transform-rotation.html why does the object only turn 90 degrees?
its rectangular on 2d if that matters
show your current code and whats happening instead, you only need 1 axis (z) for 2D
second, firing up unity
this is the code
and the thing is instead of maintaining a pace and spinning around infinitley it slows down and stops at abt 90 degrees
now i dont really understand quanternions so and explanation would be great
yes because Slerp is going from a start rotation to a target rotation
if you want to rotation just do
transform.Rotate(0,0, horizontalInput * rotateSpeed * Time.deltaTime)
also configure your IDE
alr thanks hows the target set by the way
wdym if you want to keep rotating you don't need a target
btw Quaternions are just representation of rotation in 3D space
yeah just out of curiosity since i didnt set it
just know you need to work with Euler angles -180 to 180
using quaternion for rotations prevent issues with gimbal lock
Two of the rotation axes become parallel to each other, meaning a rotation around one axis effectively affects the other, causing a loss of independent control over one degree of freedom.
https://en.wikipedia.org/wiki/Gimbal_lock
(common issue with eulers)
alright ill remember that thx alot!
just realized i did whoops
How can I make another object be actie (appear), after player collides with some object? I have a plane and sone text behind the player and I want them both to just appear (be active) after the player collides with some cube on the ground
I know it's something with OnTriggerEnter
#π»βunity-talk message
also configure your !IDE and show where you are actually increasing coinCount
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
using System.Collections.Generic;
using UnityEngine;
public class Controller : MonoBehaviour
{
public float speed;
public float maxSpeed;
public Rigidbody rb;
void FixedUpdate()
{
float vertical = Input.GetAxis("Vertical");
float horizontal = Input.GetAxis("Horizontal");
var movement = transform.forward * vertical * speed;
rb.AddForce(movement, ForceMode.Acceleration);
if (rb.velocity.magnitude > maxSpeed)
{
rb.velocity = rb.velocity.normalized * maxSpeed;
}
}
}
I made this script for a rigidbody FPS controller, but when I test the position values change but the actual object appears to not move.
could be just you have a plain background or something and with the static camera you cant see it moving?
especially if you have a 100x100 for example floor thats full white
its hard to tell if your actually moving
The ground is changed to a dark grey and the I havent messed with the camera
place a few cubes around, can you actually see yourself moving then?
nah, nothings really changed in the past few years
is your position frozen maybe on your rigidbody?
No I had the rotations froze
not really sure then, try googling it might come up with a solution
or just check each thing and make sure nothing might be blocking it from moving
I turned on interpolate and magically worked
i have recently updated to unity 6 and i cant seem to find rigidbody2d.velocity() did i miss something they changed?
thanks , bdw its same as the one before right?
yeah i think so
Check the docs for Rigidbody2D . . .
can u link me up please i am bad at finding stuff in the docs
use the search button
you could also use google
i did but i cant find the part related to my issue :V
Thanks a lot
Anyway, if you use Rigidbody.velocity your code editor should tell you to use linearVelocity instead, something like "'Rigidbody2D.velocity' is obsolete: 'Please use Rigidbody2D.linearVelocity instead. (UnityUpgradable) -> linearVelocity'"
Yes sorry , i didnt typed the whole word my bad
you literally search the name of the type and it'll pop up. it's not hard at all . . .
you searched in the manual, not the scripting api . . .
!docs
they meant the property, they were confused because Unity 6 has renamed the Rigidbody property from.velocity to .linearVelocity
ah
k...idk what to do anymore, so I have these buttons that work like this...
and then I have a moving version of pretty much the same thing and it like half works, but the particles don't change when the button is hit
what particles don't change when what button is hit?
...the first video
which particles? the ones around the triangles, or the ones on the floor?
what button is being hit?
the ones that appear when the greenish triangles disappear
ah okay i gotchu, the triangles are the buttons, i thought u meant like a key on ur keyboard
make sure your variables are referring to the right thing
too often i've seen beginners have fields referring to prefabs under the assets folder instead of the actual instantiated object that they should be referring to
oh shit whoops lmao π
can't believe it took me forever to figure that out
What are you doing with snake case?!
Change it back to camel / pascal >:(
you mean...starting with a capital letter and using underscores? is that what that is?
probably came from C++ . . .
or just the underscores
camelCase and PascalCase . . .
for runtime stuff you don't. you can use a string or an int. there are third party assets like NaughtyAttributes and OdinInspector which add stuff that allow you to pick a scene from a dropdown though, but it's still either a string or int
This is a good place to start
Some teams use different conventions but that is what I personally follow
seems everyone uses camel case and suggests it. I use snake case because I haven't really seen anything in the language that uses underscores so they kind of stand out
...although sometimes it's inconsistent π
camelCase + PascalCase. No one is using just camelCase in C#. (Well, someone might, but not most people)
C# convention uses camelCase for fields. private fields are prefixed with _ underscores. types, methods, properties, and events are PascalCase . . .
public class MyClass : MyInterface
{
public System.Action<int> IntEvent;
public int intVariable;
private int _intVariable;
public int IntProperty => _intVariable;
private void MyMethod()
{
int localIntVariable;
}
}```
though, actually, if you have public fields, they should be PascalCase, similar to properties . . .
hey guy, I'm new in Unity. Could someone provide me some tutorial to start? Thank you so much 
Check the pinned messages of the channels. This is the beginner programming channel.
Odd question, I'm quite new and am sure this is probaly really easy.
I need to swap a corpse's model to a Loot Bag on death (so this involves swapping the Mesh).
How do I go about this / where is this located in the official docs? Version 2022 if it matters.
If its not an appropriate question, I can ask in another channel.
you just destroy the corpse GameObject and instantiate the loot bag GameObject. you'll probably want to use object pooling for the loot bag if there are many spawned from defeating enemies . . .
So there is no swap mesh in place. Got it, thanks!
Hey guys, what's up...?
I'm kind of new to Blendspaces in Unity, and Unity in general to be honest
The animations were working before but I changed up my code a bit and it stopped working somehow
Someone said that my code is stuck in the "Vertical Velocity" Blendspace (it has Jump, Double Jump and Fall in it)...I'm not sure why
This is my snippet of code for my animation logic
//Animation Logic - Horizontal Movement
if(horizontalMovement == 0) {
sidAnimations.SetFloat("Horizontal Velocity", 0.0f); //Idle Logic
} if(horizontalMovement != 0) {
sidAnimations.SetFloat("Horizontal Velocity", 1.0f); //Walking Logic
if(runningAction) {
sidAnimations.SetFloat("Horizontal Velocity", 2.0f); //Running Logic
}
}
//Animation Logic - Vertical Movement
if(verticalMovement > 0) {
sidAnimations.SetFloat("Vertical Velocity", 0.0f); //Single Jump Logic
if(jumpsLeft == 0) {
sidAnimations.SetFloat("Vertical Velocity", 1.0f); //Double Jump Logic
} else if(verticalMovement < 0) {
sidAnimations.SetFloat("Vertical Velocity", -1.0f); //Falling Logic
}
}```
This is the value of horizontalMovement, basically just the X-values (after watching the tutorials on the new Input System)
I set the parameters Horizontal Velocity and Vertical Velocity (one for each blendspace), based on my player's axis movement
I'm not sure why the animation is basically locked in my Jumping blendspace...
@frank zodiac I solved slower build time in Unity 2022.3.47f1 by applying these settings
Is there a way, how I can check those Inputs without creating 6 if statements?
If you know Minecraft, there is a Hotbar down for the inventory with 9 Slots you can target with your mouse wheel. But you also can just press the Number Keys to get directly to the Inventory Slot.
My inventory is similar to this, but instead of 9 Slots, I only need 6.
bool _DirectSlotButton1Pressed = _controls.Player.Inventory_Hotbar_DirectSlot1Button.WasPressedThisFrame();
bool _DirectSlotButton2Pressed = _controls.Player.Inventory_Hotbar_DirectSlot1Button.WasPressedThisFrame();
bool _DirectSlotButton3Pressed = _controls.Player.Inventory_Hotbar_DirectSlot1Button.WasPressedThisFrame();
bool _DirectSlotButton4Pressed = _controls.Player.Inventory_Hotbar_DirectSlot1Button.WasPressedThisFrame();
bool _DirectSlotButton5Pressed = _controls.Player.Inventory_Hotbar_DirectSlot1Button.WasPressedThisFrame();
bool _DirectSlotButton6Pressed = _controls.Player.Inventory_Hotbar_DirectSlot1Button.WasPressedThisFrame();
if (_DirectSlotButton1Pressed)
{
_AktullerHotbarSlot = 5f;
_Slider_Hotbar.value = _AktullerHotbarSlot;
}
if (_DirectSlotButton2Pressed)
{
_AktullerHotbarSlot = 4f;
_Slider_Hotbar.value = _AktullerHotbarSlot;
}
if (_DirectSlotButton3Pressed)
{
_AktullerHotbarSlot = 3f;
_Slider_Hotbar.value = _AktullerHotbarSlot;
}
if (_DirectSlotButton4Pressed)
{
_AktullerHotbarSlot = 2f;
_Slider_Hotbar.value = _AktullerHotbarSlot;
}
if (_DirectSlotButton5Pressed)
{
_AktullerHotbarSlot = 1f;
_Slider_Hotbar.value = _AktullerHotbarSlot;
}
if (_DirectSlotButton6Pressed)
{
_AktullerHotbarSlot = 0f;
_Slider_Hotbar.value = _AktullerHotbarSlot;
}
Direct answer: An array and loop
Poor copy and paste btw Inventory_Hotbar_DirectSlot1Button
Thats why it would feel wrong to make it like this.
Even if this would be the only code in this script.
Is there also a solution for the Input action Map to keep this also clean?
Instead of using 6 extra actions just for an alternative keybind for the Hotbar?
I'm not too aware of the new input system but you should be able to poll input as well if you're not liking the other two methods of acquiring input (event subscription and something other that I do not remember)
C# events (code), unity events (inspector), polling in Update (code) . . .
Not sure if manually loading would be considered creating... 
I'm assuming they would have to create the actions in Unity, export as json and reimport. Unless.. they simply write it in json...
If you already have premade bindings I'd just put them in an array like Dalphat suggested with something like:
// rough example since it is very late for me lol
struct Foo {
public InputActionReference action; // w/e the type is
public int slotIndex;
// constructor
}
private Foo[] _slotActions = new Foo[6];
void Init() {
var playerMap = _controls.Player;
_slotActions[0] = new Foo(playerMap.Inventory_Hotbar_DirectSlot1Button, 5);
// etc
}
void Run() {
foreach (var slot in _slotActions) {
if (slot.action.WasPressedThisFrame()) {
_AktullerHotbarSlot = slot.slotIndex;
// do thing
break;
}
}
}
Could simplify the premade actions into generated ones, but not sure how those work with things like the PlayerInput handler, would also have to manually enable/disable/dispose them
// actual binding name is probably wrong here
// can generate them in a loop
_slotActions[0] = new Foo(new InputAction("slot_0", binding: "<Keyboard>/1"), 5);
// etc
Food for thought anyhow π
You mean its more optimized in means of performance?
no, those are the different ways you can access/handle the input. though, i agree with Dalphat and Nomnom about using arrays . . .
I'm still searching right now how did it work again, because the last time I used Inspector events was 2020
I was thinking over it now for almost an hour and I can't remember that this was even possible, without using something like a UI Button, toggle or Slider.
In my case, I only use Device Inputs, like Keyboard, Mouse and Gamepad.
I understand the thing with the array, but I don't understand the part with:
I mean I have a Slider but this Slider is not for clicking on it, only staring.
The part with the array and loop...
Are you sure this will it not overcomplicate the script and make it even harder to read than 6 if statements, in case you will visit the script again in 4 years later or something?...
But I also run in an issue here with:
_DirectSlotButton1Pressed = _controls.Player.Inventory_Hotbar_DirectSlot1Button.WasPressedThisFrame();
Because I cant make an array in the new input system action map and how can I replace the "1" with a 2,3,4,5,6 in this loop of the "Inventory_Hotbar_DirectSlot1Button", if I can't make an array in the New Input System Action map?
bool[] _DirectSlotButtonPressed_ARRAY;
for (int i = 0; i < 6; i++)
{
_DirectSlotButtonPressed_ARRAY = _controls.Player.Inventory_Hotbar_DirectSlot1Button.WasPressedThisFrame();
}```
You add the buttons to the array, not the bools
You add the array of buttons as a field in your class and iterate over that
for (int i = 0; i < _buttons.Length; i++)
{
if (_buttons[i].WasPressedThisFrame())
{
_sliderHotbar.Value = _buttons.Length - i;
}
}
are we still talking about Keyboard Buttons or UI Buttons?
Whatever "Inventory_Hotbar_DirectSlot1Button" is
What kind of Variable is _buttons?
because of
Error (Active) CS0029 The type "bool" cannot be implicitly converted to "UnityEngine.UI.Button". Assembly-CSharp C:\...Game\Scripts\Inventory\Hotbar.cs 86
UnityEngine.UI.Button[]?
Just guessing based off the message. It's an array containing whatever type Inventory_Hotbar_DirectSlot1Button is

Just... Check in the code. Hover over the reference. It'll tell you what type it is. It's really not that complicated.
I mean its not a UI Button, it is more like a location-description of this here and I think I must have the option to make arrays in there first, before I am able to make arrays in the code realated to this.
Its like the New Input system was never made for putting it in arrays.
You can put anything into arrays
You have the buttons (or actions, whichever it may be) in code, clearly
Just use them there
I don't really get the confusion
class YourFunnyClass
{
private WhateverType[] _buttons;
private void Start()
{
_buttons = new[]
{
_controls.Player.Inventory_Hotbar_DirectSlot1Button,
...
};
}
private void Run()
{
// loop
}
}
The input itself is a bool in my case.
But putting it in a bool array would also need that I would be able to put the "Inventory_Hotbar_DirectSlot1Button" into an array, what seems to not be possible because this is part of the New Input System Map. Its more like a location than a variable. Its different to how you would threat a simple Unity UI Button.
Once more, you are supposed to put the button/action into the array
Not any kind of bool
Wherever you may be getting that from
This is already what nomnom was suggesting here (though they overcomplicated it a bit)
Thanks man!
What we want to do is avoid copy/paste 6 times the same if.
But the alternative really feels a bit overengineering.
#π»βcode-beginner message
It's 3 lines of code, how is it overengineered?
You could just as well use a bool array with the approach I suggested. But that'll waste more resources
Sorry, I was still up there and trying to understand Nomnoms code, while you wrote me your new example.
What should I put in the OnCollisionEnter ()? Anything I put in gives me an error...
It's the same way you declare variables normally, the Type then the name of variable. You should probably do some c# basics if you dont know this
Figured it out, should have used an on trigger since it's a trigger and unchildren the other objects from the trigger
That's pretty unrelated to anything that was said above
This is basically what I wanted to do
Player walks over a so called "trap" (the trigger), and a plane then blocks their path backwards nd a text saying try again appears
Pretty simple, but this is actually my first ever script I wrote all by myself, so everything looks the same to me (everything is chinese)
That's why you were suggested to go and learn C# basics.
Then it wouldn't look like Chinese to you.
Were you looking at some super old documentation here because that is javascript syntax lol
Or something close to that
Learned c# basics a long while ago and still remember it since I practice c# and cpp regularly. The unity syntax looks like chinese to me. But the only problem here was that I didn't know the difference between OnCollisionEnter and OnTriggerEnter
Everything else is completely logical
There's no "unity syntax" it's the same as regular C#. And what you shared earlier definitely points out you don't understand that.
Unity doesn't change the programming language in any way. The only thing unique to unity is the API.
Just saying, the problem you initially asked was not something that could even relate to Collision vs Trigger. If you practice c# regularly you really should be familiar with how writing a method works
Wait wait wait, why nothing related to Collision vs Trigger?
Might be a little misleading from my side here
collision : UnityEngine.Collision is invalid C# syntax. That's what caused the error.
The method declaration here is not a correct syntax in C#.
Yeah that was an old post I found and thought to try it, but after changing it I forgot to change it back to what I had originally. I originally wrote OnCollisionEnter (Collider other) and in the brackets what was there originally, but that didn't work.
And that was probably right? I just didn't unchildren the text and wall from the trigger for it to work
Well that too wasn't the correct signature.
Your first problem was a syntax error, second was a logical error.
Now it works after all, got my shit togheter and realised what I was writing didn't make any sense.
As osmal mentioned, the code that you copied was probably from a long time ago, when unity used other languages, beside C#. Obviously it's not gonna work in C#.
Went back on the docs, researched it a bit more and realised I had to use OnTriggerEnter (Collider other) (which actually makes sense?)
Unity used to support javascript, you were reading a really old post
Yeah now that he mentioned it does look like js syntax
If you want trigger events, sure. If you want collision events, you still need OnCollisionEnter with a correct signature
This time I want trigger since it's a trigger trap basically
And it works pretty good actually right now
This question is weird
Your ide is supposed to auto complete known Unity methods for you
If you are trying to do this manually then I suspect your !ide is not configured. Configure it.
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
It is very easy to make mistakes with these methods since they don't have a lot of checks, but if it's not the same as what Unity suspects then it simply won't call it.
Is there any way I can get on-screen buttons to affect Input.GetAxis?
For example I want to use Input GetAxis horizontal for A and D keys, and for mobile users to press the left/right buttons
Hello, what is the best way to share project with other person?
Use git
It will be useful for all of your projects
There are two main websites to host repositories : github & gitlab
Both have their pros & cons
Is there are storage limit?
Yes. All solutions do.
storage limits are dependent on the remote host you use. github for example has a soft storage limit of about 5 gb for a repository. if you have the resources though, you can always spin up your own git server so you can use as much storage as you need
Why do people sometimes name their variables with an uppercase letter like this? Doesnβt this go against the naming conventions?
Why not just name it βhealthβ
Is there a convention for this I didnβt hear of
according to the standard c# naming conventions public members should be PascalCase. also that isn't a variable, that is a property
Oh wait so if itβs a variable with a getter and setter, that makes it a property?
it's not a variable if it has a getter/setter, it is a property. a property is used like a variable but in actuality is a group of getter and setter methods
this is why you run into issues with modify the members of a value type you get from a property. such as something like this: transform.position.x = 1; This is not valid because position is a property which means it is a getter method returning a copy of the position
And you do whatever you want with the naming of your variable, even though standards exist, you do you at the end of the day
Id prefer to follow the standards
Makes sense
While this is valid advice, I suggest you stick to conventions where possible to avoid conflicts with other developers, should you work in a team
how do i connect my lever class to the class i want to interact with ```cs
public class Lever : MonoBehaviour, Interactable
{
public Animation LeverAnimation;
public bool CanInteract = true;
public string HoverText => "Use Lever";
private float InteractTime = 0;
public void interact()
{
if (CanInteract)
{
CanInteract = false;
LeverAnimation.Play("lever");
}
}
void UpdateInteractiontTimer()
{
if (!CanInteract)
{
AnimationClip Clip = LeverAnimation.clip;
InteractTime += Time.deltaTime / Clip.length;
if (InteractTime >= 1)
{
InteractTime = 0;
CanInteract = true;
}
}
}
void Update()
{
UpdateInteractiontTimer();
}
}
presumably your interaction system is raycasting and checking for an Interactable component, so that's all you need to do. that should then call the interact method
ye but its just a lever, how do i make a modular system where the lever fires a method from another class
give it a UnityEvent then you just hook it up in the inspector
and just invoke the event at the appropriate time during your interaction
ah i see, thought i had to make an abstract class or something
nah, that's not necessary. using the unityevent will allow you to be more modular here since you can then use this to interact with pretty much anything you want
and if the unityevent is public you can even subscribe to it from other objects in code instead of just the inspector. that would allow you to subscribe non-public methods to the event so that the event can be the only thing that calls those specific methods
Which Unity doesn't allow you to do a lot of the time
Of course you can, you just have to accept that Unity hasn't done it with their exposed variables
You can still do it fine with your own code
Calling them "variables" is a bit wrong to begin with. They all have their own names. You probably mean "fields" in this case.
fields are variables. they are class level variables
A variable is a general term. In C# they are more specifically called a field (when part of a class scope)
I might accept "instance variables"
It literally means "a value that can change"
but a field can be static which means fields are not all instance variables
a field is literally just a variable that is declared directly in the object. it is a variable. calling it a variable is not wrong. my point before was that properties are not technically variables, they are a set of methods that are used like variables
The nuance and naming is difficult around this
it's really not. a field is literally defined as "a variable of any type that is declared directly in a class or struct"
To be specific on variables; in C# we call them a field when it's on the class scope and a local variable when it's in the method scope.
Mhm
Like if you say "declare a variable on the class", I wouldn't be entirely sure if you mean a field or a property
They're both "variable"
An auto-property, you could argue, is a "variable"
A property is not a variable, it doesn't hold a value
While it might look like it does, it will use a backing field most of the time. This means the backing field is the variable in this case.
It effectively does through the backing field
it's still got a separate field that is assigned by the getter and setter, it's just implicitly created by the compiler instead of explicitly created by the coder.
if you want to be pedantic about what is and is not a variable, then you should not be referring to properties as variables
And yes, this is often reason for confusion
Yes, so it's not the property that holds the value
It's a bit petty to make that distinction
How is it petty? There's a clear difference, you're just confused by what syntactic sugar allows here
Heh, I'm not confused, I know C# inside and out
If that didn't exist, you'd have to explciitly declare a backing field each time.
Then surely you'd understand why a property is not an actual variable being mutated each time
I mean in reality it isn't, but coming back to this, it's not really clear what's meant by "variable" in a context like this
Just imo
Especially because I don't think fields should be public. If I'm meant to add a "public variable", I'm adding a property
Which is where I come back to unity not being able to conform to these standards, you can't use properties in the inspector, right?
so you have a self imposed 'standard' and you wonder why others do not conform to you
you can serialize a property's backing field, either by targeting it with the attribute target for an auto property, or just serializing the explicit backing field
This isn't that self-imposed
yes it is 'I don't think fields should be public' is self imposed
either way though, it doesn't call the setter or getter because those are actually methods
using System.Collections.Generic;
using UnityEngine;
public class PipeSpawnerScript : MonoBehaviour
{
public GameObject Pipe;
public float spawnRate = 2;
private float timer = 0;
public float heightOffset = 10;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if (timer < spawnRate)
{
timer = timer + Time.deltaTime;
}
else
{
spawnPipe();
timer = 0;
}
void spawnPipe()
{
float lowestPoint = transform.position.y - heightOffset;
float highestPoint = transform.position.y + heightOffset;
Instantiate(Pipe, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint)0, transform.rotation);
}
}
}
what is wrong here i dont understand>
Neither do we
make sure your !IDE is configured so you get your errors underlined, once you see it you'll kick yourself lol
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
Care to elaborate a bit on what is actually going wrong
you have nested the spawnPipe method
they're only calling it from the method it is nested inside of so that isn't an issue. they have a compile error on the last line of actual code
two actually
yep, nonsense Vector3 initializer
Local methods, although an abomination, are legal.