#💻┃code-beginner
1 messages · Page 561 of 1
Ah those icons somehow flipped. It works fine when I click on the back side. 
Are you using Cinemachine?
nope just the regular camera component
Is it an orthographic camera?
yup
In that case, you can pretty easily calculate how far the camera is allowed to move
The orthographic scale is how many units of space the camera covers
Here's the current script: https://pastecode.io/s/exc0vzdr
I believe it's the vertical size of the camera
ah, it's half of the vertical size
So you can do something like this
[SerializeField] Transform cornerOne;
[SerializeField] Transform cornerTwo;
[SerializeField] Camera camera;
void ClampCamera() {
Bounds bounds = new Bounds(cornerOne.position, Vector3.zero);
bounds.Encapsulate(cornerTwo.position);
bounds.size = Vector3.Scale(bounds.size, new Vector3(1,1,0)); // ignore any Z positions
bounds.extents -= camera.orthographicSize * Vector3.up; // shrink the bounds vertically
bounds.extents -= camera.orthographicSize * camera.aspect * Vector3.right; // shrink the bounds horizontally
Vector3 current = camera.transform.position;
current.z = 0; // also ignore the Z position
Vector3 clamped = bounds.ClosestPoint(current);
clamped.z = camera.transform.position.z;
camera.transform.position = clamped;
}
ew, kind of messy looking
You construct a Bounds out of the two corners, then shrink the bounds
exents is the half-size of the bounding box, so it lines up correctly with orthographicSize being half of the vertical size of the camera
camera.aspect is width / height, so that gives you the orthographic width of the camera
This might blow up if you wind up with a negatively-sized bounding box
thank you 🙏
oops, typo on the second to last line; fixed
why isnt this working ```using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SelectionManager : MonoBehaviour
{
public GameObject interaction_Info_UI;
Text interaction_text;
private void Start()
{
interaction_text = interaction_Info_UI.GetComponent<Text>();
}
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
var selectionTransform = hit.transform;
if (selectionTransform.GetComponent<InteractableObject>())
{
interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();
interaction_Info_UI.SetActive(true);
}
else
{
interaction_Info_UI.SetActive(false);
}
}
}
}``` The error is Assets\Script\SelectionManager.cs(10,5): error CS0246: The type or namespace name 'Text' could not be found (are you missing a using directive or an assembly reference?)
am a beginer so this is straight copied from yt
If i use "this" in base class constructor, does it return the derived class instance or the base class has its own instance?
It's actually the derived class but you can only access the members of the base class from it
so can someone help orrrrrr
Or maybe show a piece of code of what you mean
It's been 3 minutes
Ah i see, thanks. So it returned the derived class but it is treated as the base class, am i correct?
sorry
Are you sure you copied the tutorial correctly? You are indeed missing a using directive in the top
I didnt copy the part from the top
Show example code of what you mean so I know we are talking about the same thing?
Only ```public class SelectionManager : MonoBehaviour
{
public GameObject interaction_Info_UI;
Text interaction_text;
private void Start()
{
interaction_text = interaction_Info_UI.GetComponent<Text>();
}
void Update()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
var selectionTransform = hit.transform;
if (selectionTransform.GetComponent<InteractableObject>())
{
interaction_text.text = selectionTransform.GetComponent<InteractableObject>().GetItemName();
interaction_Info_UI.SetActive(true);
}
else
{
interaction_Info_UI.SetActive(false);
}
}
}
}```
it is just a thought exercise, i dont have code
when i pick up the bomb it for some reason doesn't let me jump ?
can someone help me
Are you just talking about cs class A { public A() { this.integer = 123; // Error } } class B : A { public int integer; }?
@queen adder
you need to add the namespace
but you better use TMP instead
uhh maybe? i already said i dont have code, i was just wondering how "this" works in base class, i dont have code
It is just logical exercise
Okay, well the base class doesn't know anything about its derived classes
using UnityEngine.UI;
Even though it can be one of its derived classes
it is the derived class, constructing a subclass doesn't create an extra object for each parent
but the base doesn't know (and shouldn't care) what specific subclass it is, so it can only access stuff it knows about, aka stuff it defines and stuff it inherits
Okay thanks
okay wait 1 sec
Why would you mention someone just to tell them to wait a second 😆
waited and waited nothing
But yeah TextMeshPro is preferred
okay new errors
Assets\Script\SelectionManager.cs(28,73): error CS0246: The type or namespace name 'InteractableObject' could not be found (are you missing a using directive or an assembly reference?) and Assets\Script\SelectionManager.cs(28,73): error CS0246: The type or namespace name 'InteractableObject' could not be found (are you missing a using directive or an assembly reference?)
so do not look for the gameobject then look for the Text componenet just directly use a reference to the text. but as mentioned you will be using tmp anyways so do not bother
so what did i do
how much big string we can give as input
i gave it this string to parse and it said invalid value
-12.7157
any ideas how to fix it
or is there another way
ChangeTransformValues(transform1, V("-3.8778 13.1071 14.0333"), Q("270 267.4232 0"), V("459.6276 -1.7346 269.4254"));
This should parse just fine unless it has some invisible character after it.
{
string[] strArray = input.Split("\\s+");
return new Vector3(float.Parse(strArray[0]), float.Parse(strArray[1]), float.Parse(strArray[2]));
}```
{
string[] strArray = input.Split("\\s+");
return new Quaternion(float.Parse(strArray[0]), float.Parse(strArray[1]), float.Parse(strArray[2]), 0f);
}```
or it is splitting falsely
do you have a script/class named InteractableObject
Show it
according to your error you don't, show that
why are you even using strings for this
easy to store i guess
Or it's in a namespace or assembly definition
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 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.
it is
true
any ideas how to fix such errors?
well you showed the filename not the the class name
no? not at all
whats the "class name"
How so? Where are you storing it? How is it easier than storing a Vector3 or Quaternion directly?
the name next to the keyword class?
public class Foo
Foo is the class name
Show the code
i am just trying stuff
not really effecient at the moment
for the InteractableObject?
yes
yes
ok i will do it the primitive way
just use new Vector3(x, y, z) instead of V("x y z")
thank you tho
When you're told to check something, you should probably actually check it instead of just assuming you did it right
well I thought I didnt know what was the class name
thats all
dont be afraid to ask
Then you should ask that, instead of saying "It does match"
very true. If you don't ask what something is, you cannot learn
i don't think you should be constructing Quaternions manually either
it looks more like you're using eulerAngles
that's not what the quaternion constructor does
all good lol did you get it working?
yes
How do I regenerate the #C project/solution files ( Unity 6, 6000.0.32f1, LTS ) ?
there is a button in External Tools in Edit
or you can delete them iirc Unity will just regen them
@fluid remnantdeleted them, it doesn't regenerate
And I don't have that button in Unity 6
Did you open project again after delete ?
And if you don't have the button in your edtior then you never configured your IDE properly to Unity
How can I open the project? it's deleted 😅
@fluid remnant it's an "old" (pre-6) project I upgraded - in previous version the button was there
Then you haven't correctly configured your !IDE 👇
If your IDE is not autocompleting code
or underlining errors, please configure it.
Select one:
•
Visual Studio (Installed via Unity Hub)
•
Visual Studio (Installed manually)
•
VS Code
•
JetBrains Rider
• :question: Other/None
looks like you manually linked your IDE which is wrong, you have to follow the proper setup
check the links boxfriend sent
@fluid remnant it looks like the steps I've done previously, and I tried to do them again now (removed the visual studio package and re-instaled it) - but in the list I only have the "Internal" version
show you have Unity Workload installed in VS Installer
Did you properly add the unity vworkloads when installing? (it isn't automatically done for you)
also you don't need 2019. that will just create more friction in configuration
Click modify and make certain that you've installed the Unity workloads and install them if you haven't.
@ivory bobcat that's the screenshot I just sent?
I can still open a backed-up version of my project in 2022.3.55f1 btw, and everything is great in there
hmmm looks okay if its installed, something else might be wrong
I don't think this is pc-related but rather project or version related, just not sure what
those are typically not Project bound but Editor version bound
do you have any compile errors or anything ?
I do, a lot.
Right now I can't show them because I tried to delete the solution and project files, and I can't generate them.
The issues I had were about missing dependencies, such as Image from unity.
I added the unity.UI to my assembly, and it still didn't work.
Which is why I wanted to regenerate the solution/project files
Right now this is the error:
I had the same issues, Visual Studio just stopped detecting Unity namespaces
I tried to delete all caches btw - even the ones from the preferences
.. what did you do?
I ended up using VSC lol
Tried to create a new empty project btw and it works there - so it's my specific project that has the issue.
I can't just start a new one though 😅
Gonna try and match packages
you tried updating all your packages in this project?
yup, of course
on unity 6 ? check Test Framework cause that seems to have been updated since 2021
mines at 1.4.5 but I'm on Unity 6.0.23f
@fluid remnant oh looks like I'm on an old "Pre" version 😮
Let me try play with that
that should ideally remove that obsolete error
oh I (vaguely) remember, I needed version 2 for something - even though it's old
I was also missing the 2D Feature btw, which I believe it's something new.
ok restarted the editor and things are starting to look much better now!
Still checking though
I am trying to install NCalc via Unity Nuget package but it is conflicting with Visual Scripting, how do I solve this? Library\PackageCache\com.unity.visualscripting\Runtime\VisualScripting.Flow\Framework\Formula.cs(16,17): error CS0576: Namespace '<global namespace>' contains a definition conflicting with alias 'NCalc'
yesss regenerate is there, and no longer internal version
@fluid remnant thank you!
nice! np
if you don't need VisualScripting why not just remove the package
I use VS for state machines
check pins in this channel
also the pathways on !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
Wow what an annoying problem this is
Unity hijacked the NCalc namespace in their code :F
maybe alias it like what I do with my own grid classusing Grid = G.Grids.Grid;
And why does sending a bug report take 30+ minutes attaching 3 files?
@west radishI tried, but since the NCalc DLL exposes NCalc its not possible because the conflict happens when its loading all assemblies
I would need to recompile NCalc myself with its own name
(I think)
I don't come from a C# background
https://github.com/ncalc/ncalc https://docs.unity3d.com/Packages/com.unity.visualscripting@1.8/api/Unity.VisualScripting.Dependencies.NCalc.html are these two not the same thing?
I dont really know what I'm looking at with either of these
idk, I think they made some kind of adaption of it
Actually I'm gonna try use the built in version and see if it works without my third party import
I saw this but that is 5 years old
not too sure then
I'd guess the one unity has is the same
maybe try and access something from the original ncalc, from the one unity provides
using NCalc = Unity.VisualScripting.Dependencies.NCalc.Expression;
Using directive is unnecessary.IDE0005
The type or namespace name 'NCalc' does not exist in the namespace 'Unity.VisualScripting.Dependencies'
Can't seem to import it in my code
remove .Expression;
otherwise NCalc will refer to the .Expression part of the namespace, not ncalc itself
Yeah I tried all combos, it seems the API isn't the same as in the original package because I get delegate errors
It's because they are expecting a flow state machine in their version...:
public delegate void EvaluateFunctionHandler(Flow flow, string name, FunctionArgs args);
Gah
Actually, it's not just 3 files; I just noticed that the report to be sent includes all the project files. From the attach files section below, remove the main project folder, select the folder required for the report, or don’t attach any files at all. This way, you can send it quickly. 
Oh okay, guess they got the entire project then
Is there some kind of global DI in Unity since I can't import conflicting namespaces and wrap them?
The project breaks instantly when I import the package, even without any scripts
see #854851968446365696 for what to include when asking for help
Hey, so I am making a Player script for my mobile game so that when I press the LeftMoveButton it moves left, when I press RightMoveButton, it moves right. but I have an error he is the code with the error https://hastebin.com/share/obegodakah.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
By the way, I am I new creator/scripter so I am having a little bit of trouble with coding
Input.mousePosition returns a vector2
it is the screen position of the mouse, it would not make sense to assign it for a transform
a transform is a component that contains position , rotation and scale properties
You need to convert the screenposition (X,Y) to a World Position XYZ
which would be a Vector3 not a Transform
I am new, so I need some help doing that please?
How do I conert a screenposition to a world position
its easy steps to lookup, broke it down to you as much as I could
okay
literally type this into google. Look what happens. Ofc put "unity" in the search too
I promise you its that easy
if you're brand new though, I would start with the pathways on unity !learn
:teacher: Unity Learn ↗
Over 750 hours of free live and on-demand learning content for all levels of experience!
It had told me to add a "Camera.main.ScreenToWorldPoint" in there and I did, but I still have the same error
because thats only part of it, you ain't gonna be using that 1 line of code and suddenly this bad logic makes sense
the code you wrote is nonsense for now
Left/Right move buttons are not Transform, that makes no sense
No, I have 2 buttons, I have 2 Transforms as LeftMoveButton and RightMoveButton
wdym you have 2 Buttons ? what kind of buttons
When the player touches one, it moves in that direction
here...
I am in simulation mode btw
so why are they transform? that makes no sense
Okay, I don't know how to make a button for mobile...
want to do something specific when button is Held you need to use the EventSystem and the proper method for performing an action based on that button held/pressed
did you lookup how to make on screen buttons? the internet is filled
well guessing your way through it will not work well lol You have to research the components you want to use
you as well 🫡
best of luck
Where is the default assembly definition list? I can't find it, I am sure I have seen it before. Also I can't disable visual scripting "auto reference" since its definition file is all greyed out
the default assembly definition list
What is this?
I can't disable visual scripting "auto reference" since its definition file is all greyed out
You can't generally modify packaged unles you convert them to embedded packages.
What are you trying to do?
Trying to get NCalc to work without conflicting with the hijacked NCalc namespace of visual scripting :F. Isn't there a list somewhere of all the assemblies that are included in the project? I am trying to see if I can take this package from nuget, and wrap it somehow in its own namespace so it wont collide...
Are you actually using the Visual Scripting package?
I use it for my visual state machines
Can I not assign a .DLL to my custom asmdef?
How do I reference this in C#?
assuming you are working within that assembly you've just defined, you just start using the types defined in that dll you referenced in the asmdef
My script is not in the same folder
well that would be the problem then
So what do?
if you want to be using that assembly you have defined that has the reference to that dll, then you must be working within that assembly by putting your code within the same folder (or child folder) as the asmdef
if you don't want to be using asmdefs, then just don't use them and make sure the dll is in your project
So there is no way for my script, outside dir directory to call this dll with its custom namespace?
wdym "with its custom namespace"? because that root namespace you've defined in the asmdef has nothing to do with that dll, it's just the namespace that would be automatically added as the root for scripts created within that assembly
mmm kay. Is there any other solution to wrap a .dll namespace that conflicts with Unity packages?
what does "a .dll namespace that conflicts with Unity packages" even mean here?
The NCalc namespace is hijacked by visual scripting package, the use a modified version of this public project
So.. I can't import it and use the "real" one
in what way is it "hijacked" by visual scripting
I have an issue but its so dumb i feel like it makes 0 sense, whenever my player collides with an object tagged "end level" its coded to remove the constraints of all the platforms so they fall. This works but for some reason when i collide with the object from the top (fall down on to it), it still removes the constraints but they just dont fall?? I've messed with the colliders and a bunch of other shit but its still like this
I have the same problem as this guy: https://discussions.unity.com/t/cannot-use-ncalc-due-to-namespace-conflicts-caused-by-visualscripting/1556005
so you have those errors in the console?
Yep
And I seem unable to wrap this library because the moment I import it, it conflicts
what are the rb properties of each platform
also why are they grouped ?
and you can't simply just use the version of that dll that is included in the visual scripting package with the using alias as described?
move the package from Library/PackageCache, to Packages in your project, by it it becomes embeded package so you can change it. Then look for the issue and fix it.
No, because they modified it to expect a flow graph...
only the empty "Platforms" object as an rb and they are grouped so i can easily remove all their constraints
rather than having and removing constraints it would probably be better to make them kinematic then switch them to dynamic.
As for why they don't fall, they might be asleep.
Ok i will try what you said but what do you mean by asleep is this a joke
not a joke
@hot laurelWhat package, the NCalc? I can't modify the dll tho?
Rigidbody can be "Asleep" or Awake"
Awake meaning its actively running simulation.
Asleep means its paused
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rigidbody2D.WakeUp.html
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rigidbody2D.Sleep.html
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rigidbody2D.IsSleeping.html
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rigidbody2D.IsAwake.html
Visual Scripting package, since the error in console indicates the source its from there
You can modify everything
That would be a nightmare to maintain 😄
Thanks it worked
Assemblies from packages scripts as for assets scripts are compiled and stored under Library/ScriptAssemblies, so once you move the package as i guided before you can edit the script alonez which cause problems
I find it weird that you can't wrap a DLL somehow
When you created your custom assembly def directory, how do you expose all the stuff in there to other dirs?
how can i detect if i clicked on an object with the new input system? its quite difficult for me
use the IPointerDownHandler interface, and if it's a world space object it needs a collider and your camera will need the relevant physics raycaster component. and you'll need an EventSystem in the scene if you don't already have one
god that sounds intimidating
Invoke raycast on mouse click in short
should work exactly the same. All it changes is the Input Module to the new one (assuming its UI)
it's really super easy. just implement the interface and use the quick actions to actually implement the relevant method, that will be the method that is called when the mouse clicks that object. the rest is just scene setup
omg I actually did it
I wrote a wrapper and exposed it through my assembly def directory, and now I don't have the namespace problems
Wait, i need raycaster to use iPointerDownHandler?
Also, the OnMouseDown method says that it works in GUI, but it doesnt, does it require additional components? (has image component on it)
OnMouseDown does not work with the Input System
and you need the physics raycaster if the object is in world space
No like, the thing that appears when you hover on method, says that it works in world space and GUI space, it means thats wrong?
wdym by "that thing"? if you mean the OnMouseDown method that does not work with the Input System
Im not asking about the input system
then why are you replying to a message where i was answering how to do that for the input system
but anyway, if you're using the IPointerDownHandler on a world space object, you do need a physics raycaster on the camera and the object needs a collider. that's just how that works.
the xml comments that are left on methods and can be viewed when hovering on method say that OnMouseDown method works in world space and GUI space, yes it does work with colliders but it says that it works in GUI space, and i assumed that it would work like iPointerDown
next time you have a question just ask it directly in the channel instead of pinging someone who was answering a different question about it
There was 2 separate questions, 1 about iPointerDown and second about that
i separated them with word Also
I am making a 2D game for my phone but when I try to move it won't move with the UI Legacy Buttons even after I set them up to call movements can someone help me figure out what to do? here is the code: https://hastebin.com/share/gujezohaco.csharp
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
that is very wrong. you should go through some basic c# courses so you can learn how methods work
Wdym very wrong? Did I mess something up?
you should go through some basic c# courses so you can learn how methods work
there is absolutely no reason whatsoever that should work
Bruh, you have update calls on all your methods
Oh wait thats not supposed to be there.
You should do the unity tutorials
All Update methods except the one on line 49 won't get called by Unity
you should def go through c# basics
This code does almost no action
I messed up rq I'm fixing
"almost no action" is kind of an understatement considering the only line of logic that actually runs is the one line in Start
This is far from messed up 😄
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
I fixed it but It still no work
now do you understand why the previous code was wrong?
yes.
alright, why was it wrong
but it still n work
probably because you aren't calling the methods
bc I accidently put update in every method
that's not why it was wrong, that was what you did. why was that wrong.
I thought that was why it was wrong
I'm calling them in the unity legacy ui buttons
so you don't actually understand why that was wrong, you just know what you did that was wrong.
as i said before, you should go through some beginner c# courses so you can learn how methods work
put logs in the methods and see if they are called
ok
when i set skill1(Keycode variable) to a letter it works but not when i set it to a number it doesnt. Any idea why? if (Input.GetKeyDown(KeyCode.Alpha1)) { spells[0].Use(); } if (playerInputManager.Skill1()) { spells[0].Use(); }
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 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.
friction
Wdym set it to a letter ?
just to confirm, you are pressing the 1 key in the number row above the letters, right?
yes
ooo ok grax 
and you don't have some stupid keyboard that requires some other key combination for that to actually be considered the 1 key, right?
Yes, the methods are being called
so its working
how do you call Skill1()
No, the player still isn't moving
like what does the bool do, sorry
exactly as shown. Again it works when i set it to a letter, it just wont work when i set it to a number
{
return Input.GetKeyDown(skill1);
}```
I think its a unity 6 bug
well how often are you pressing the button because AddForce will not do much in 1 frame unless you called Impulse
Impulse?
How did you define skill1? It's a KeyCode?
yes
like ForceMode.Impulse
default for AddForce i think is acceleration
@drowsy oriole did u make a physics material and apply it to ur rigidbody
no
if you print out the value of skill1 does it show the correct keycode? if yes, then i'd just try restarting the editor real quick since that can fix some weird bugs with the input manager
so i would do "rb.AddForce.Acceleration"?
no ForceMode is a second paramater for add force, check the docs
default is ForceMode.Force
this blinded ne
lol
I have a EditorWindow.
Why won't this clear the UI from the entered input when I press the button (or how do I get it to update in the UI?)
private void OnGUI()
{
GUILayout.Label("Chat Window", EditorStyles.boldLabel);
chatLog = EditorGUILayout.TextArea(chatLog, GUILayout.Height(200));
chatInput = EditorGUILayout.TextField("Message", chatInput);
if (GUILayout.Button("Send"))
{
chatInput = "";
}
}
Oh okay. Still thats too slow to do much in 1 frame right? I think they are using OnClick button
The default forcemode is generally intended to be applied over multiple frames, yes. Like a continuous force.
where is it in the docs?
Okay so you need to either change the ForceMode to use impulse or use maybe a different method for UI for Holding button to apply over multiple frames
it's right there in the docs for the AddForce method
are you looking here
https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rigidbody2D.AddForce.html
fixed edit lol
oh shoot you're right they are using 2D
And as a question how would I add a holding button?
You cannot use OnClick you would need one of the EventSystem methods
Like this?
maybe enable a bool on Click n disable it on release then use FixedUpdate to move based on those bools
there are dozens of tutorials for on screen controls you could be following
PointerDown i think is one frame but you can use that to do the bool thing
this is exactly what i was doing and thats why it didnt work. Keypad 1 is my side numbers. I should have set it to alpha 1
it was set to alpha1 in your screenshots though 🤔
I was just wondering if any of you guys knew how to fix this error Im getting. Im new to Unity and trying to make a simple animation where my character moves down. When I drag the character into the animation window, it gives me the option for spriteRenderer or playerControl. When I click on one of those, it gives me a null pointer exception. Im dragging the hero_1.png image into the animator cause I want to create key frames of the character walking. Is it because of the file format being png? I dont know why I cant drag it and why im getting a null pointer exception. Dont know whats null.
#🏃┃animation not a code question.
Hey i have download this pack on uas and now in my game i have 4 erreurs and I can't fix them how can help me please i'm beginner
and if I don't fix them I can't code and play anymore
not a code issue
delete your library folder
and upgrade all packages
dang beat me to it. update packages first, if the issue persists after that then close the editor, delete library folder, and launch project again
deleting the library folder triggers a reimport of all packages and assets which usually fixes issues like these if updating the package doesn't just fix it
ok i will try
i have upgrade all packages and i only have these two errors
if the issue persists after that then close the editor, delete library folder, and launch project again
eh yes
this one ? (sorry for telling a lot of questions)
yes
From the package manager
that folder is automatically generated by unity and contains cached content like the packages, it will be regenerated once you open the project again
it might take a while to open the project though, probably as long as it did the very first time you created the project, plus some extra time for importing any other assets/packages you've added since
Okayy
yes i have update from package manager
it's normal ? 😅
If this project is using HDRP then it shouldn't have the post processing package installed anyway
So if it's actually meant to be using HDRP, then uninstall the package
so i need to uninstall post processinf package ?
maybe my google-fu is just bad today, but is there a concise list of Attributes? like:
Inspector Attributes
[Header(string)]: Adds a header above the field in the Inspector.
[Tooltip(string)]: Adds a tooltip when you hover over the field in the Inspector.
[Range(float, float)]: Allows you to restrict a float or int to a range with a slider.
Thank you very much!
Not that I'm aware of, and not sure how complete or not that github link is, but if you use your IDE to follow, for example, to open the PropertyAttribute class and then search for usages of it, you should see the usages of it, you can see all deriving types.
but just me I want to use post processing and not hdrp how do I do it?
hoo i'm so dumb
That is a good idea! so far, i have found the Definition, but still looking for the 'list' that comprises it. I will keep looking, as this is mostly my lack of experience with the IDE than anything else. Thanks! 🙂
What IDE?
Depends on which IDE. For Rider it would be right click -> Find Usages.
why is this point specifically counted as the "spawn point" of my tilemap object? ie, when i instantiate a new copy of this object from the red gizmo object, it spawns like this rather than from the corner of the map
code spawning the room within the gizmo object
i keep getting this, but i will mention here when i figure it out
Cannot navigate to the symbol under the caret.
Select the thing you want to interrogate
that's the position you are passing in. It's the position of the object the script is attached to. (transform.position)
yes i know, i mean why does it build the actual tile map around that position like that/count that as the start point for the tile map rather than the top right corner or middle
wdym by "it" building the tilemap around that position? How did the tilemap get built? Didn't you place the tiles manually?
i start by going here
Which leads me to the second image
which then leads me here
PS make sure you have this set to Pivot
yep now right click PropertyAttribute and "Go To Implementations" or something
the tilemap is a prefab (image 1 showing full object) i placed, im confused why it isnt being placed like this(image 2) or this(image 3) in comparison to the gimzo (the hallway is a child of the object)
If i do that while into the last image, of the class, it tell me Cannot navigate to the symbol under the caret.
But if i do that from here it only shows me third party
almost like it cannot decompile the dll, but i am sure it can access that info. So i guess a bit less straight-forward in VS (or i am just clueless, which is also true 😆 ). I will keep looking. thanks, both, for the pointers
I'm not sure I understand these images as the pivot seems to be in the same place in all three.
the pivot is yes, which is what i am confused about why it is there rather than where the red gizmo is in the second or third image. like is there a reason/way to change it?
it's there because that's how you created it
You placed the tiles where they are placed
you can of course move the tiles if you wish
i am in the PropertyAttribute Class itself, and there is little there. pretty much for defining custom property attributes, according to the comments.
It almost seems like the information about the actual arguments are stored in .dlls and VS does display that, readily, where perhaps Rider does.. not sure.
'322' items in cache
------------------
Resolve: 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'
Found single assembly: 'netstandard, Version=2.1.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'
Load from: 'C:\Program Files\Unity\Hub\Editor\6000.0.32f1\Editor\Data\NetStandard\ref\2.1.0\netstandard.dll'
------------------
Resolve: 'UnityEngine.SharedInternalsModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
Found single assembly: 'UnityEngine.SharedInternalsModule, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'
Load from: 'C:\Program Files\Unity\Hub\Editor\6000.0.32f1\Editor\Data\Managed\UnityEngine\UnityEngine.SharedInternalsModule.dll'
------------------
Resolve: 'System.Runtime.InteropServices, Version=2.1.0.0, Culture=neutral, PublicKeyToken=null'
Found single assembly: 'System.Runtime.InteropServices, Version=4.1.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
WARN: Version mismatch. Expected: '2.1.0.0', Got: '4.1.2.0'
Load from: 'C:\Program Files\Unity\Hub\Editor\6000.0.32f1\Editor\Data\NetStandard\compat\2.1.0\shims\netstandard\System.Runtime.InteropServices.dll'
------------------
Resolve: 'System.Runtime.CompilerServices.Unsafe, Version=2.1.0.0, Culture=neutral, PublicKeyToken=null'
Could not find by name: 'System.Runtime.CompilerServices.Unsafe, Version=2.1.0.0, Culture=neutral, PublicKeyToken=null'
#endif
hey all, will this script work if both the ladder and the player (the script is attatched to the player) are prefabs? it doesnt seem to be working and im wondering if its because the image and player are prefabs (its a multiplayer game)
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.
What i am doing right now only requires basic attributes, so i will set the hunt aside for now, and use the provided git list
objects being prefabs doesn't really mean anything to the engine.
In fact once you spawn them into the scene, the spawned instances are no longer prefabs.
Sounds like you are kind of just guessing in the dark at what your problem is.
The best approach here is to systematically debug your code.
Certainly one thing to do is check your console window for errors
alright ill check now
you should always have the console window showing un Unity, and always be looking at it more or less.
this is my script setup
it just prints 'ladder' theres no errors
but the prompt icon doesnt show up
i think i found the issue
Then it's all working fine
it changes the actual prefab and not the one in the scene
Ah then you have referenced the prefab
instead of the one in the scene
ohh
but it doesnt let me reference the onein the scene for some reason
Because prefabs cannot reference objects in scenes directly
ohh
is there a way to get around that? like can i spawn the image prefab in afterwards?
Of course.
Here's a good explainer on some simple ways:
https://unity.huh.how/references/prefabs-referencing-components
Assets can't directly refer to Objects in Scenes, but their instances can be configured with those references.
thank you
this works like a charm tysm for your help <3
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.
what do i need to do here?
is it possible to create new c# script via
..
it put it in twilight or something this is my Temp/Local AppData folder
the coins variable isnt increasing when i am colliding with the coin itself, but its still printing the debug phrase any help?
Show your console in Unity and show the inspector of the coin manager and what you assigned to the text field
Yes it is possibble to create new file via VS. Like any other file system explorer creation. Rest of the question is hard to decode.
So you have an error happening. You should have mentioned that already
yeah im not sure why though
i tried to see what it was but it doesnt make sense to me
Look at the line it points to
show the inspector of the object w the script
o wait nvm its on trigger
your player rigidbody is missing
Seems relatively clear to me the player doesn't have a reference to CoinManager.
But the error says which filename and line number to look at. You should look there.
wheres the script
It's clear to me too, just trying to teach them to debug.
in the playercontroller script i put cm as a reference
Look at the filename and line number of the error
It's in your player script
And based on the error we can see you failed to assign that reference
do i need to drag it into my project directory each time? b/c i dont see where it choses to create it
and theres no New > selection in the right click menu like Code for example
i looked for a location in the settings.. and successfully found some.. but they're for other things like project templates, user item,..
next time i'll just drag the file into the asset folder..
i just assumed it'd know to put it in where my solution is pointing
add> Add new Element, when you press on solution/solution dirs
there are templates to pick so you can pick c# script, or just write the file name manually with .cs extension lol
am I going crazy, I can't figure out why a method isn't being called
...
Debug.Log("HIT TARGET");
if (linkedAI)
{
Debug.Log("AI EXISTS");
linkedAI.TakeDamage(amount);
}
}```
I have this code in Target script
and then in the EnemyAI script I have
public virtual void TakeDamage(double amount) {
Debug.Log("TOOK DAMAGE");
}
and then in the subclass I have
public override void TakeDamage(double amount)
{
ChangeToState(AIState.PAIN);
Debug.Log("PAIN");
base.TakeDamage(amount);
}
but neither of those debugs shows up
HIT TARGET shows and AI EXISTS shows
and the compiler doesn't throw an error
so how is it not running those methods???
{
playerState = gameObject.GetComponent<PlayerState>();
listener = gameObject.GetComponent<AIEventListener>();
linkedAI = gameObject.GetComponent<EnemyAI>();
maxHealth = health;
}```
This is how Target sets its linkedAI variable and I see it in the inspector being set properly
am i missing where the target function is being calldd
yeah but I mean I see HIT TARGET in the log so it IS being called
but when it's called, the TakeDamage methods are not being called it would seem
since I get no Debug for those
so u get debug.log AI EXISTS but not PAIN
log linkedai instead of ai exists?
ok
ooh I see
I forgot there was an old disabled script on that object
of the same supertype
ah
thanks, sorry for being dumb
lol dw
im watching a tutorial and his code says 'origin:', how do i make it so it says this, it seems helpful? is it a certain ide?
That's Jetbrains Rider, it recently became free for non-commercial use
ooo okay imma use that thanku
I believe that VS and VSCode also have that option but yeah I can recommend Rider
i tried looking for it in vs, couldnt find it
WHY IS THE INSTALLER 1.4GB 😭
My install is like 5GB
ohhh makes sense
this is so much easier it auto completes everything for u
Your previous IDE probably just wasn't configured
quick question, should i move into learning c# basics first for me to understand dotts?
or can i just go into dotts directly if i knew some easy c# stuff
Absolutely. DOTS is not easy
perfect thanks for confirming dude!
protected override void OnSpawned()
{
base.OnSpawned();
enabled = isOwner;
playerCamera.gameObject.SetActive(isOwner);
crosshairImage.enabled = true;
}```
this makes it so only the host has the crosshair enabled, how do i make it so everyone has the crosshair enabled?
i dont want them to have the crosshair in the server selection, only when they spawn into the game
just simple event based system which update the ui according to loaded scene/ game state, by updating UI i mean enabling/disabling crosshair
thanx
using UnityEngine;
public class RotationMimic : MonoBehaviour
{
[SerializeField] private Transform mimicObject;
private void Update()
{
if (!mimicObject)
return;
transform.rotation = mimicObject.rotation;
}
}```
why is my gun stretching like that
Because its parent has a non-uniform scale
Meaning the X, Y and Z are not the same
This will cause rotated children to be skewed
You could set that scale to 1, 1, 1 and put the capsule/other graphics into a separate child instead, and scale that
fixed it ty!
I have hit a stone wall with my snakegame. I have a problem I have been unable to fix. Is there a particular format to present my code and unity settings to someone who knows how to troubleshoot it?
This is the first unity project ive worked on so I would appreciate any form of guidance
screenshots for the setup, and see below for how to post !code 👇
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 Inline Code
Surround code with three backquotes. Not quotation marks.
To format as C#, add cs to the first line:
```cs
// Your code here
```
Add a comment with a line number if there is an error message.
also see #854851968446365696 for what to include when asking for help
Thanks. When I have prepared a document for a helper to read, is this the right channel to post it in?
if it is a code question, yes
Well… i dont know if it is. Im having problem with my game.
okay well you haven't even said what you're having trouble with
you should be able to describe the problem. it has to fit under a category: art, unity editor, code (programming), etc . . .
Context: This is the Snake Game. The intention is to recreate Snake Game to begin to grasp the fundamentals of Unity programming. I have created Four walls, a Snake Head, Food, and a Snake Segment. I have created a Snake Movement Script for all the coding, from controls to triggering the Game Over.
The Problem:
As soon as my Snake Head makes contact with the first Food object, it automatically produces a Snake Segment. However, the Game Over is instantly triggered as soon as the Food is touched. The Console debug indicates that my Snake Head is automatically colliding with the Snake Segment produced.
My Troubleshooting:
- Collider Settings Checks
- Physics Layering Checks
This is the beginning of the document I was writing to present when I knew where to go to ask for help.
we don't need an entire novel about your issue. just a description about what you are having trouble with and the relevant details
I am making snake game to learn unity. The one where the snake eats the food to grow longer and longer.
When my snake eats the food in my game, however, it automatically collides with the segment it creates and game overs.
you didn't need to rephrase what you've already said. just show the relevant code and setup
how do you check for a game over? can you show that code?
also, the code for the contact with the food object . . .
Game Over Code: https://pastebin.com/Ft3YTYM9
Food Code: https://pastebin.com/6xM2gzfp
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.
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.
I also have console logs if you think it will help
'StartCoroutine(AddSegmentWithDelay())' im blind or the implementation of Add Segment is not included here?
Oops i hadnt added it since the game over code was requested.
Here’s the Add Segment Code: https://pastebin.com/wdWd66sx
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.
!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
If you have problem with a segment triggering unintendent game over it would be natural and logical to include the code without a request
In hindsight, you are right
probably the offset of generating new segment is too close to the snake
so it triggers the collider
is there a way to test for the players light level?
im trying to make it so when your in a dark area your sanity goes down slowy and when your in a lit up area your sanity goes up slowy
you can move new segment further back by fixed size or just disable snake segments colission, and give to head other tag than snake segment
Ive commented out all mentions of game over so i can see what exactly is going on. I have tried multiple edits to add segment and nothing’s changing it so that the segment spawns outside of the head. Every time it spawns it’s only just slightly offset, regardless if it’s 0.5f, 1.1f, -0.5f, etc.
It probably requires a picture to make sense what’s going on though
Ok so right now I'm just trying to make a basic side scroller game where you go forward and dodge obstacles, very basic set up, mostly just trying to learn unity on my own
I've gotten a movement system to work and it can work fine, but instead of adding the full amount of speed whenever I press a button, it instead slows down and ramps up in the other direction like a car would
This is the code I got right now, is there some other method I can use to make the movement instantaneous?
{
public Rigidbody rb; // allows for interaction with the rigidbody in the script
public float forwardspeed = 1000.0f; // how fast the player goes forward
public float horizontalSpeed = 1000.0f; // how fast the player goes horizontally
private float horizontalInput; // allows the player to go left and right
// Update is called once per frame
void FixedUpdate()
{
rb.AddForce(0, 0, forwardspeed * Time.deltaTime); // Adds forward foce
if (Input.GetKey("d"))
{
rb.AddForce(horizontalSpeed * Time.deltaTime, 0, 0); // Moves right
}
if (Input.GetKey("a"))
{
rb.AddForce(-horizontalSpeed * Time.deltaTime, 0, 0); // Moves left
}
}
}```
horizontalInput is a left over from something else I was trying
Is it recommended for a programmer to use code for doing everything even assigning references through code instead for inspector in editor for less mess?
I think very much "it depends". like, do ihave to program a GetComponent, and then several of these that end up taking time, or is it a simple
var = var thing?
one of the neat things about Unity, is that you Can use the Inspector like that.
Perhaps program in Checks, to make sure that things are not missed, because that is also easy to do when dragging things into inspector.
I suppose, do what it most efficient, in the end.
maybe, if a thing is not going to be changed, set it up in code, as long as it is efficient.
But, while designing, if i want to play with the color of a light, lets say' i do not want to change code all the time to do that, so i would make it a field in the inspector.
The Actual programmers would have better advice, but as a solo dev, that is my simple take on it
yea exactly, no one is going to see how you did it, they are gonna see how efficiently you did it at the end, good advice
Well you're using the physics engine and adding forces. It's going to behave realistically. If you want to have instant acceleration you can just directly set the velocity instead of using forces.
That makes sense
Can I not have two body.velocity at the same time?
{
horizontal = Input.GetAxis("Horizontal");
body.velocity = (transform.right * horizontal) * horizontalSpeed * Time.fixedDeltaTime; // Player moves left and right
body.velocity = (transform.forward) * forwardSpeed * Time.fixedDeltaTime; // Sets how fast you go
}```
I've got this as my new velocity based movement, but when I have both it can go forward but won't move side to side, but when I dash out the forward it can mvoe side to side just fine
you can have as many as you want, but naturally the last one will overwrite any previous data
You need to combine it all into one vector
You can just add vectors with +
by the way
you should NOT be using Time.fixedDeltaTime here
or any time adjustment at all
So just have that be 0?
velocity is simply velocity. It's expressed in meters per second
just get rid of it
if you multiply by 0 your whole vector will become 0
Ok well that was why I had to put like 500 just to move at any decent speed
so I can just do something like
movement = New Vector3(body.velocity horizontal, body.velocity forward, 0)
huh? no
Vector3 right = transform.right * horizontal * horizontalSpeed;
Vector3 forward = transform.forward * forwardSpeed;
body.velocity = right + forward;```
something like this
Ah
That seems to work, thank you very much
Looking at it for longer, the structure of it begins to make more sense than what I had
drag and drop to unity Project window?
ok
Please use the proper channel next time. This is a coding channel
ok sorry
very opinionated topic!! im one of those who prefer doing things in code than in inspector.
But I still do things in inspector for those that makes sense, like assigning references. To make sure the programmers assign reference properly, there is always 'assert'.
besides, when editing a single line, even adding comments, unity takes years to recompile it. I might die before it finishes. Inspector is better for this.
That said, with code you can easily track where thing is used. And is searchable.
one of the most annoying thing is UnityEvent. if I wanted to modify it like fixing bugs or adding feature, if you connect it through inspector, it will be a torture to make sure all other thing that uses this event is not broken. especially IF i am forgetful, working with programmers with various skill level, and the project is big.
if there are tools that help with this, I may have different opinion.
personally I think people should just do whatever their team members agreed. and only changes things if it sucks.
Hello!
I'm struggling with Essentials Pathway which requires you to make a VFX on a Player model, when all collectible are collected.
So the script is basically working well, and it does spawn VFX on needed location but....
-
It creates thousands of clones in the hierarchy window even with a bool statement which should break the loop.
-
VFX does not emmit (no confetti)
You'd have to show the full code.
can I test the player light level and convert it to a value?
Alr
!code
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 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.
Since you do:
bool collected = false;```
Then collected will ALWAYS be false when it comes to
```cs
if (collected == false) {```
basically you might as well not have an if statement at all with the way this is set up
you just created that variable and set it to false, and then you check if it's false
It will always be false
I set collected = true; but due to being in a different block, it's not being changed?
on line 59 you set it to true, which will only matter for it to get printed as true on line 63, after which the method ends and the variable disappears entirely
it's being changed just fine
it's just a local variable
Oh
local variables only exist inside the scope they are declared
and they stop existing after that
that varible only exists inside the function and only while the function is executing
the next time you call the function you're creating a brand new variable with
bool collected = false;```
and initializing it as false
So.. If I say:
bool collected = true;
It will be changed to a public variable? And it won't disappear?
no
"public" is not relevant here
what is relevant is the scope of your variable
and where and when you assign values to it
Isn't public like making turning it off "invisible" so entire script can access it?
no
not at all
you are confused
Forget about public
that's not important here
I thought private is being used when something is not useful in a long run and you don't need it in future, and public makes script to remember that thing and edit later
you need to worry about the difference between:
- A local variable
and - A member variable / instance variable
No. You have completely the wrong idea about these things
forget all of that, it is wrong.
Alright alright
public and private is not relevant to our discussion at all
that's for something else entirely.
This is what we care about right now.
I got it
public class Example {
int memberVariable = 6;
void SomeFunction() {
int localVariable = 4;
}
}```
This is what we are worried about
You have a local variable
Yeah
You probably want a member variable
Is it that one on the top?
the one called member variable of course
because void is like. nothing
A okay
Yeah I see
Oh wait I think I got it
No I don't
Like if I write in the line 54 that collected == true
It will just ruin everything
you're not understanding what I'm saying
I never said to do that
Why would you do that
I don't
Your problem is that collected is a local variable
you need to make collected a member variable
AHHH
I think I got it now
If I put it on line 10, it will be always stored in public class (beginning of the script)
And script can change it and access
if it's a member it becomes part of the script
I'm confused
it lives as long as the script does
(which usually lives as long as the GameObject it's attached to)
Yeah
Your code is running every frame, right?
You have information you are trying to store across frames
So you need to store it somewhere that survives across frames
such as on the script itself.
Yep
A local variable only lives as long as the function takes to execute
usually a few nanoseconds
and then poof it's gone
Yepp
So as I said if I put it to the top, where are variables are declared, I will make this variable to live forever
basically local variables are for temporary storage inside a function to facilitate the function, that's it.
Not forever, but as long as the instance of the script lives, yes.
Yeah, for some not needed info for a long run
really "at the top" isn't as important as "inside the class, but not inside any function"
I've never seen the $ before a debug, what does it do?
It has nothing to do with the "debug". It's string interpolation
In this particular case it doesn't do anything
You would do something like:
Debug.Log($"There are {_playersAlive} players left alive");```
ohh okay good to know
and that will print the current number of players alive (or whatever is stored in that variable)
ohh right
It's kind of a nicer way of writing:
Debug.Log("There are " + _playersAlive + " players left alive");```
good to know for the future, thanks :)
You said inside the class, so I can place that line everywhere (but not in Update and Start and so on)
yes.
Not that I would recommend it
but yes
And as you said, inside the class, but not in the function, else it will be a private variable
Where is the best place? Before start?
It's up to you, but convention is typically at the top of the class, yeah
Sometimes people but some declarations in void Start() why?
Isn't everything before Start() being executed as well?
They do not put declarations in there, unless they are using local variables inside Start.
What they might do is initialize some variables that were declared outside.
A lot of the times they aren’t declarations rather initializations, which would probably be better in an Awake method
Oh yeah, that's what I saw
Uh yeah, something like
rb = GetComponent<>() ;
But can't you do it outside?
Or it's like
"Just once and forever"?
You can do it in any method but if that rb is being used in multiple methods or across your script, you’d want the variable initialized when the script is first called
you cannot call non-static methods outside of a method, no.
No GetComponent outside
you really can't.
It’s being called inside a method
private void OnCollisionEnter is a method?
Yes
yes...
Sorry if that's a dumb questions, I'm really new to unity
its not about unity
method and function basically mean the same thing, by the way
you can use them interchangeably
Functions are more familiar to me, so I'mma try to remember 2 meanings okii
They’re usually referred to methods in C# because of the language’s encapsulation overall but in C/C++ they’re referred to functions
"method" is just the word for "function attached to an object" in object-oriented programming. Since C# is object oriented, almost all functions are methods.
Oh alright, thanks for clearing it @wintry quarry @keen owl
And one more last thing, what does it require for particle to work when being copied?
On my previous game engine there was a special function called Emit()
Pathway requires to spawn a confetti on the player's model, when all collectibles are being collected (the script is finished with that bool variable), but particle doesn't emmit for some reason.
Although made almost the same way as original collectible (tutorial related)
you can set up a visual effect to just play as soon as it's created
otherwise you can call Play() on it
It does copy, but it does not emmit anything, is there a key difference between EmptyParent game object and original game object?
(or more advanced, set up your own events)
Oh, I think there is one located outside of the map, and the original one (tutorial one) is made as a prefab
Maybe that's why
Yayyy!! It works!!!! Tyyyyy guyss
(I dont know where to ask this) How would you guys make an interaction "system"? So like opening doors or picking up stuff. I have been watching it all over youtube and most of the tutorials are outdated.
I would give a Door script to the door object which implements the IInteractable interface on the door. Then, your player fires constant rays which checks if there is a gameobject in front. If this is the case, use TryGetComponent<IInteractable>() and get the script. Finally, call the Interact method implemented in this script, and open/close the door
Picking up stuff works the same, but Interact gives the pickup to the player
If I were you I'd give the player as the context through a parameter in Interact for things like that
An interface works perfect here to make something interactable because you are able to add a small requirement like this very easily to a general Door/Pickup class which might have much more to it
Never used Intercaes btw, so I will have to learn...
For example, if your Door were destructible you'd be able to add an IDestructible interface
Do that, interfaces are very important to understand
Thanks!!
Feel free to ask once you have a general understanding
why does it give 300 ammo after i reload if clips are 30
I believe you have been told multiple times how to post !code. Use them
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 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.
'''cs
using System.Collections;
using Unity.VisualScripting;
using UnityEngine;
public class GunController : MonoBehaviour
{
[Header("Gun Settings")]
public float fireRate = 0.1f;
public int clipSize = 30;
public int reservedAmmoCapacity = 270;
//Variables that change throughout code
bool _canShoot;
int _currentAmmoInClip;
int _ammoInReserve;
private void Start()
{
_currentAmmoInClip = clipSize;
_ammoInReserve = reservedAmmoCapacity;
_canShoot = true;
}
private void Update()
{
if(Input.GetMouseButton(0) && _canShoot && _currentAmmoInClip > 0)
{
_canShoot = false;
_currentAmmoInClip--;
StartCoroutine(ShootGun());
}
else if(Input.GetKeyDown(KeyCode.R) && _currentAmmoInClip < clipSize && _ammoInReserve > 0)
{
int amountNeeded = clipSize - _currentAmmoInClip;
if (amountNeeded >- _ammoInReserve)
{
_currentAmmoInClip += _ammoInReserve;
_ammoInReserve -= amountNeeded;
}
else
{
_currentAmmoInClip = clipSize;
_ammoInReserve -= amountNeeded;
}
}
}
IEnumerator ShootGun()
{
yield return new WaitForSeconds(fireRate);
_canShoot = true;
}
}
'''
it doesnt work
and i havent been told
Surround code with three backquotes. Not quotation marks.
nobody else has a problem using it also, large code blocks go in a paste site
using System.Collections;
using Unity.VisualScripting;
using UnityEngine;
public class GunController : MonoBehaviour
{
[Header("Gun Settings")]
public float fireRate = 0.1f;
public int clipSize = 30;
public int reservedAmmoCapacity = 270;
//Variables that change throughout code
bool _canShoot;
int _currentAmmoInClip;
int _ammoInReserve;
private void Start()
{
_currentAmmoInClip = clipSize;
_ammoInReserve = reservedAmmoCapacity;
_canShoot = true;
}
private void Update()
{
if(Input.GetMouseButton(0) && _canShoot && _currentAmmoInClip > 0)
{
_canShoot = false;
_currentAmmoInClip--;
StartCoroutine(ShootGun());
}
else if(Input.GetKeyDown(KeyCode.R) && _currentAmmoInClip < clipSize && _ammoInReserve > 0)
{
int amountNeeded = clipSize - _currentAmmoInClip;
if (amountNeeded >- _ammoInReserve)
{
_currentAmmoInClip += _ammoInReserve;
_ammoInReserve -= amountNeeded;
}
else
{
_currentAmmoInClip = clipSize;
_ammoInReserve -= amountNeeded;
}
}
}
IEnumerator ShootGun()
{
yield return new WaitForSeconds(fireRate);
_canShoot = true;
}
}
This is what would be considered a large code block
_currentAmmoInClip += _ammoInReserve;
should be amountNeeded
it gets red lined if i change ammo in reserve to amountNeeded
what? Now you can post a screenshot
why the_ ?
it's amountNeeded, not _amountNeeded
ok
reloadamount = min(clipSize - clipCount, reserve)
clipCount += reloadAmount
reserve -= reloadAmount
it works ty
Is there a way to get the number of columns in a grid layout group? I'm trying to make the inventory usable with mouse and keyboard and controller, and when the player hits up or down, I want to select the item above or below the current item in a grid layout group.
I'm using Invectors 3rd Person Controller but unlike in the demo my characters movement is very floaty and sometimes my character just goes in the ground for 1sec. Does anybody know why that happens?
is there a constrained axis or is it just doing its thing
cause there is constraintCount
its doing its own thing. But now I've found out about unity's navigation system 😮
is there any noticeable difference between Lerping in FixedUpdate and Update?
it depends on t i think
typically you'd want to put it in update though, unless you're lerping something physics based, like velocity
I would say the difference would be the same as the general difference of frequency between Update and FixedUpdate
It would be less smooth
I don't see why you'd use it in FixedUpdate
Lerp is not physics related
Unless your framerate dips
^ 
That's why t exists
I don't see why FixedUpdate would improve anything over just properly handling t
Just properly interpolate between the two values with deltatime
I've just started learning unity and my first project i created is flappy bird , now i did run into many issues along the way but fixed them with chatgpt and google but one issue that i cant fix is that now that ive built my game when i run my game then close it it still keeps running in the background, some ppl said its a bug with unity 6 so i should switch to unity 2022 , is that true or whats the solution otherwise?
i haven't used much of unity six. though, if you're new to unity and haven't done anything too complex yet, downgrading shouldn't cause many issues for you
anyone know how to fix this error?
whenever i download it and try to upload it to itch.io it says filename not found
Hello! Is there a way to add a custom ID to a new VisualElement created with C# ?
yes, use the userData property
Set its name?
also #🧰┃ui-toolkit
Perfect ty! "name" is working 🙂
I'm too much in web logic, I searched for something like "attribute.id" etc.. ^^
Hello, I'm trying to trigger an animation of running while the velocity of the player is not 0 laterally. It works fine but the trigger/parameter/transition keeps repeatedly firing.
How can I make the firing occur once?
This is the code I use:
if (rb.velocity.x != 0f || rb.velocity.z != 0f)
{
animator.SetBool("runTrigBool", true);
}
else { animator.SetBool("runTrigBool", false); }
The image attached is my animator
this is my transition form Any State -> Run
make sure it can't transition to self
also consider setting a float and doing the logic in the animator
It's generally a bad idea to compare floating point values using equality. 0.000001 != 0 for example, and in many cases basic operations will cause values to never become exact.
Instead compare the sqrMagnitude of velocity with a small value
how to make sure of that?
open the settings menu
also that isn't a trigger, that's a different kind of parameter
yeah it's a bool
yeah just clarifying since you named it trig and also mentioned a trigger
you don't have any triggers there
yep I'm aware, I'm just using a naming convention that's easier for the way my brain is wired lol
is this count as health bar?
i use transforms.localSacle to sacle the player green health bar in UI. this took me a while because i need to carucate the number and other.
Then i'm done with this code
public class PlayerCode : MonoBehaviour
{
private float healthPoint = 100f;
void Update()
{
greenBarScaleX = healthPoint * 0.01f;
greenHealthBar.transform.localScale = new Vector3(1f + greenBarScaleX, 1f, 1f);
}
}```
which kinda work but since i'm using float the health bar scale isn't accurate but i can take it.
better use an ui image with fill type
i mean it not image UI but it a panel. panel act like the same right?
sorry what
does it "count"? Sure it counts. Is it the best way to do it? No.
There's no such thing as a "panel".. when you create a "panel" via the menu, it just creates a gameobject called 'Panel' with an image on it
well since i'm just a new programer, i say it was a good job beacuse i figure it out myself;
ok see you all next day when I be working on my First Ai enemy. (this gonna be hard).
i know this is likely personal preference, but is it more optimal to use multiple scripts for one (for example) enemy or just a big script?
ie. BossMain, BossController, BossAttack
if they're modular, and don't really depend on each other, you could split them up
depends on what kind of system you're going for
it would likely be very interconnected
is it much more optimized to use multiple?
or is that just for ease of use depending
Generally classes should be for one purpose. EG: a movement script doesn't need to know about sound.
This book talks about it and explains it well https://gameprogrammingpatterns.com/
cheers
or read it online for free, scroll down
Sounds pretty standard for a book
ah ok i see thanks
not really a code question #⚛️┃physics
oh k
@echo copper !code 🔽
📃 Large Code Blocks
Use links to services like:
https://paste.mod.gg/, https://hastebin.skyra.pw/ , https://paste.ofcode.org/ , https://paste.myst.rs/
📃 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.
ow, ok
code of sonic
A tool for sharing your source code with the world!
code of rays
A tool for sharing your source code with the world!
btw you can format links to have title by using markdown
[link-label here](url)
ok
so what exactly are you trying to accomplish and what is happening instead of that?
ok, i try to make sonic rotate and move along the slope, but this happens
these points under sonic are points where ray collides with ground
ohso you want it to move along the slope ?
yes. that's what sonic physics based on
shouldn't you be using something like V3.Project or ProjectPlane ?
trig is my weakness sry
no..?
i have never tried it
cause I don't see anywhere in your code using normal of the thing you hit
no, he should find the angle between points, not the normal of ground
but i can try these v3project or projectplane
Oh I guess I use it for CC and its different, i use Normal for slopes and other calcs like that
so, you are recommending me to use normal, right?
Don't use transform to move an object that has a rigidbody
Idk I just saying I use that to get the angles, you don't have to
Physics won't work correctly if you do
it just for test it on velocity, my body is kinematic
even still move the RB.MovePosition for accurate collider simulation
urm... what?
this thing if its kinematic https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Rigidbody.MovePosition.html
this gives other physics objects more accurate collider/physics hits from this kinematic body
it don't even move
sonic don't even moves
wdym doesn't move? you are forcing to move with transform.position this will give you wonky reactions from other physics objects/colliders
if you have a swinging hammer or obstacle and it hits the player it might not register as well
Unity is running 2 scenes the normal one you see and the Physics one, if you move transform you are forcing the physics to always play "catch up" usually
It wont fix the slope issue but its just something you should consider doing regardless lol
ok, so should i try normal?
yeah like Vector3 slopeDirection = Vector3.ProjectOnPlane(moveDirection, hit.normal); something like that
in ray code or in sonic code?
thats up to you. hit.normal is the raycast hit
you can also rotate the object with the normal
Quaternion targetRotation = Quaternion.FromToRotation(transform.up, hit.normal) * transform.rotation; I think.
okay, thanks. It looks workable
I try to use these methods more cause my trig is not very good lol yes gamedev its all over the place
i understand ya
tnx
also use one of the sites in the #854851968446365696 bot message for code. Pastebin sucks
I have working on a school project, but I can't figure out how to make phidgets work with menu navigation. To anyone with experience with this, could you please help me? (I am also a beginner to coding, so I do not understand everything )
phidgets?
you talking about the accelerometers ?
if so look like it even has an API for c#
Wikipedia says it's a physical device like a knob or button you plug into the computer
Something like the physical equivalent of a UI element
just a fancy name for an encoder then
maybe... it can piss you off but... can you tell me how ProjectOnPlane works?
its a thumbstick that I am using. Here is the link a link explain the basic usage
https://www.phidgets.com/education/learn/projects/unity/thumbstick/
anybody?
like, the math behind it, or what it does?
always check the documentation https://docs.unity3d.com/6000.0/Documentation/ScriptReference/Vector3.ProjectOnPlane.html
What exactly are you unsure of?
how can i find the normal of the ground player touch with this
Oh cool. I used other controllers, but mainly arduino but seems similiar process. WHat are you having issues with? also showing the setup you currently have would also help
Pass the normal from your hit raycast to this function
I am having trouble making the thumbstick interact with the canvas layer.
this thing doesnt find normals, it just spits out a direction
do you have inputs so far?
I see you should get back some floats
you can def use that to navigate menus
I am new to unity, so I am not sure how to do that . :/
This would probably involve the InputModule / new Input System
or you can just maybe make your own system using an array
then just turn your float into an integer and scroll through that
doing it through the EventSystem/InputModule would probably be cleaner but harder to pull off. You have to know how the Navigation system works
Last I checked, phidgets does not work with the new Input system. https://www.phidgets.com/phorum/viewtopic.php?t=9875.
don't worry about that
whats important is you're working with a float value
forget the hardware for now
I also foolishly to jump straight to C# from block code, so I am missing some fundamental knowledge. Could you give me an example of how to do this?
Hi! I want to make an infinite tilemap for my 2D game. I already managed to generate noise over all the plane from a given seed so that I only have to save the player-altered tiles, but my current challenge is to be able to actually explore the infinite map and to save the player-altered tiles. How can I do that/What are good sources on how to do that? Also, should I make a thread for this so that I don't interrupt?
there are built in methods usually, yes having basic c# knowledge would help you greatly here because now you got two chainsaws to juggle (unity specific API and c# basics )
unity has a built in class for example Mathf. that can turn floats to ints in various ways (these are usually common across diff languages)
cause they are math functions, like ceiling, flooring, rounding, truncating etc
ty. I will try to figure it out form here. Can I dm you if I have any more questions?
just ask here
many people here who have years of experience even more than me, or less but know more so don't be shy to ask 🙂
I'm learning just like you
whats the hotkey in visual studio that makes you type over your code
cause i accidently pressed it and i dont know how to turn it off
insert you mean?
makes you write code as if you were in Vm
why do keyboards actually come with an insert key?
yeah, but it has to be a very small percentage of people who really make use of it
i use it as a hotkey for leaving discord calls
I have a 60 so its a pain to even enable it lol
60 what?
keyboard 60%
ooohh
(because all the other keys are useful in other ways)
wow come to think of it my discord keybinds are all pretty weird
I used to have a foot pedal that I used for push to talk
my led lights up the primary keys but not the fn shortucts 
rate my keybinds
From what I found, it might be the case that a tilemap is not the right tool to approach this! They use shaders instead and some high-powered stuff I'll have to wrap my head around before implementing it. The game I'm trying to clone is infinite minesweeper so I will be dealing with tilemap updates and very big data structures to save the player progress, and it seems like SetTile is a very slow function, so yeah I'm feeling pretty lost here.
afaik i tilemap has its own optimizations compared to using an individual gameobject per tile.
so there is that to consider
Yes I read about those optimizations, but there were some cons on updating the tilemap
if each gameobject is just a static tile that doesnt do much you might incurr more bottleneck if they are all gameobjects
yeah but you can also split into different tilemap "chunks" so you dont update old tilemaps that dont need to be touched
also there are bulk tilemap setting functions iirc
how inifinite are we talking here , and do you ever see the older tiles (this is important to consider if you need to recycle the old)
look up settilesblock maybe? idk that much abt it tho
Uhh what do you mean by older tiles? Currently the board has sidelength equal to the amount of ints, but the camera has the position in floats to you can't reach there without having floating point precision loss on the camera.
Well not actually because I can't render that but the noise does reach there and can evaluate whether there will be a mine or not
hello guys hlep
i need help w my script cause my bunny is moving weird
i can stream or record
You'll have to give more details than that, and sharing the code too. "Moving weird" can mean literally anything.
Explain how you want the bunny to move, how it's moving instead, and share the code.