#💻┃code-beginner

1 messages · Page 561 of 1

deft ridge
#

How do I have a camera stay within certain boundaries? I'm making a fighting game where the camera zooms in and out depending on players positions, but I don't want it to zoom out so far it leaves the boundaries of the background like it does here

charred heart
#

Ah those icons somehow flipped. It works fine when I click on the back side. UnityChanSalute

deft ridge
swift crag
#

Is it an orthographic camera?

deft ridge
swift crag
#

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

deft ridge
swift crag
#

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

deft ridge
#

thank you 🙏

swift crag
#

oops, typo on the second to last line; fixed

jade musk
#

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

queen adder
#

If i use "this" in base class constructor, does it return the derived class instance or the base class has its own instance?

verbal dome
#

It's actually the derived class but you can only access the members of the base class from it

verbal dome
#

Or maybe show a piece of code of what you mean

verbal dome
queen adder
jade musk
verbal dome
# jade musk sorry

Are you sure you copied the tutorial correctly? You are indeed missing a using directive in the top

jade musk
verbal dome
jade musk
#

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);
        }

    }
}

}```

queen adder
ebon lance
#

when i pick up the bomb it for some reason doesn't let me jump ?
can someone help me

verbal dome
#

Are you just talking about cs class A { public A() { this.integer = 123; // Error } } class B : A { public int integer; }?

#

@queen adder

frail hawk
#

but you better use TMP instead

jade musk
#

so idk whats that

queen adder
#

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

verbal dome
#

Okay, well the base class doesn't know anything about its derived classes

frail hawk
verbal dome
#

Even though it can be one of its derived classes

naive pawn
jade musk
verbal dome
#

Why would you mention someone just to tell them to wait a second 😆

frail hawk
#

waited and waited nothing

verbal dome
#

But yeah TextMeshPro is preferred

jade musk
#

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?)

frail hawk
#

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

snow warren
#

i wanted to ask something

#

in float.parse(string input)

snow warren
#

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

verbal dome
#

How are you getting that string?

#

Show your actual code

snow warren
#

ChangeTransformValues(transform1, V("-3.8778 13.1071 14.0333"), Q("270 267.4232 0"), V("459.6276 -1.7346 269.4254"));

verbal dome
snow warren
#
        {
            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

fluid remnant
polar acorn
fluid remnant
naive pawn
snow warren
jade musk
polar acorn
fluid remnant
polar acorn
eternal falconBOT
fluid remnant
snow warren
fluid remnant
naive pawn
jade musk
verbal dome
fluid remnant
polar acorn
snow warren
verbal dome
#

Okay, well using strings when not needed is bad practice

#

And shit for performance

jade musk
fluid remnant
#

yes

polar acorn
#

yes

snow warren
jade musk
#

okay 1 sec

#

oh nvm

#

the class name was diff

#

💀

naive pawn
jade musk
#

thank you tho

polar acorn
jade musk
#

thats all

rocky canyon
#

dont be afraid to ask

polar acorn
fluid remnant
#

very true. If you don't ask what something is, you cannot learn

naive pawn
fluid remnant
jade musk
#

sorry then

#

didnt see it

#

thanks tho

fluid remnant
#

all good lol did you get it working?

jade musk
#

yes

untold plank
#

How do I regenerate the #C project/solution files ( Unity 6, 6000.0.32f1, LTS ) ?

fluid remnant
#

or you can delete them iirc Unity will just regen them

untold plank
#

@fluid remnantdeleted them, it doesn't regenerate
And I don't have that button in Unity 6

fluid remnant
untold plank
#

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

slender nymph
eternal falconBOT
fluid remnant
#

check the links boxfriend sent

untold plank
#

@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

fluid remnant
ivory bobcat
fluid remnant
# untold plank

also you don't need 2019. that will just create more friction in configuration

untold plank
#

@fluid remnant need it for something else, not unity related

#

and workload in 2022:

ivory bobcat
# untold plank

Click modify and make certain that you've installed the Unity workloads and install them if you haven't.

untold plank
#

@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

fluid remnant
#

hmmm looks okay if its installed, something else might be wrong

untold plank
#

I don't think this is pc-related but rather project or version related, just not sure what

fluid remnant
#

those are typically not Project bound but Editor version bound

#

do you have any compile errors or anything ?

untold plank
#

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:

fluid remnant
untold plank
#

I tried to delete all caches btw - even the ones from the preferences

fluid remnant
untold plank
#

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

fluid remnant
untold plank
fluid remnant
#

mines at 1.4.5 but I'm on Unity 6.0.23f

untold plank
#

@fluid remnant oh looks like I'm on an old "Pre" version 😮
Let me try play with that

fluid remnant
#

that should ideally remove that obsolete error

untold plank
#

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

robust condor
#

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'

untold plank
#

yesss regenerate is there, and no longer internal version

@fluid remnant thank you!

fluid remnant
robust condor
#

I use VS for state machines

proper field
#

What's the best way to learn unity?

#

My goal is 3d game development

fluid remnant
#

also the pathways on !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

robust condor
#

Wow what an annoying problem this is

#

Unity hijacked the NCalc namespace in their code :F

west radish
robust condor
#

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

west radish
#

I dont really know what I'm looking at with either of these

robust condor
#

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

west radish
#

seems like it might be the same

robust condor
#

I saw this but that is 5 years old

west radish
#

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

robust condor
#
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

west radish
#

remove .Expression;

#

otherwise NCalc will refer to the .Expression part of the namespace, not ncalc itself

robust condor
#

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

glossy jetty
robust condor
#

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

slender nymph
drowsy oriole
#

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

#

By the way, I am I new creator/scripter so I am having a little bit of trouble with coding

fluid remnant
#

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

drowsy oriole
#

I am new, so I need some help doing that please?

#

How do I conert a screenposition to a world position

fluid remnant
drowsy oriole
#

okay

fluid remnant
#

I promise you its that easy

#

if you're brand new though, I would start with the pathways on unity !learn

eternal falconBOT
#

:teacher: Unity Learn ↗

Over 750 hours of free live and on-demand learning content for all levels of experience!

fluid remnant
drowsy oriole
fluid remnant
#

the code you wrote is nonsense for now

#

Left/Right move buttons are not Transform, that makes no sense

drowsy oriole
#

No, I have 2 buttons, I have 2 Transforms as LeftMoveButton and RightMoveButton

fluid remnant
drowsy oriole
#

When the player touches one, it moves in that direction

#

here...

#

I am in simulation mode btw

fluid remnant
drowsy oriole
#

Okay, I don't know how to make a button for mobile...

fluid remnant
#

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

drowsy oriole
#

No, my wifi is horrible

#

but I will try thank you

fluid remnant
#

well guessing your way through it will not work well lol You have to research the components you want to use

drowsy oriole
#

Happy New Year!

#

bye

fluid remnant
robust condor
#

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

wintry quarry
robust condor
#

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...

wintry quarry
robust condor
#

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#?

slender nymph
#

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

robust condor
#

My script is not in the same folder

slender nymph
#

well that would be the problem then

robust condor
#

So what do?

slender nymph
#

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

robust condor
#

So there is no way for my script, outside dir directory to call this dll with its custom namespace?

slender nymph
#

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

robust condor
#

mmm kay. Is there any other solution to wrap a .dll namespace that conflicts with Unity packages?

slender nymph
#

what does "a .dll namespace that conflicts with Unity packages" even mean here?

robust condor
#

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

slender nymph
#

in what way is it "hijacked" by visual scripting

misty pecan
#

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

slender nymph
#

so you have those errors in the console?

robust condor
#

Yep

#

And I seem unable to wrap this library because the moment I import it, it conflicts

fluid remnant
#

also why are they grouped ?

slender nymph
hot laurel
robust condor
#

No, because they modified it to expect a flow graph...

misty pecan
wintry quarry
misty pecan
robust condor
#

@hot laurelWhat package, the NCalc? I can't modify the dll tho?

fluid remnant
#

Awake meaning its actively running simulation.
Asleep means its paused

hot laurel
#

You can modify everything

robust condor
#

That would be a nightmare to maintain 😄

hot laurel
#

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

robust condor
#

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?

wispy coral
#

how can i detect if i clicked on an object with the new input system? its quite difficult for me

slender nymph
#

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

wispy coral
#

god that sounds intimidating

hot laurel
#

Invoke raycast on mouse click in short

fluid remnant
slender nymph
# wispy coral god that sounds intimidating

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

wispy coral
#

ill try

#

thanks

robust condor
#

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

fringe plover
slender nymph
#

OnMouseDown does not work with the Input System

#

and you need the physics raycaster if the object is in world space

fringe plover
#

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?

slender nymph
#

wdym by "that thing"? if you mean the OnMouseDown method that does not work with the Input System

fringe plover
#

Im not asking about the input system

slender nymph
#

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.

fringe plover
#

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

slender nymph
#

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

fringe plover
#

There was 2 separate questions, 1 about iPointerDown and second about that

#

i separated them with word Also

drowsy oriole
#

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

slender nymph
#

that is very wrong. you should go through some basic c# courses so you can learn how methods work

drowsy oriole
#

Wdym very wrong? Did I mess something up?

slender nymph
#

you should go through some basic c# courses so you can learn how methods work

drowsy oriole
#

YOU should tell me what I did wrong

#

Because, unless im stupid, this should work

slender nymph
#

there is absolutely no reason whatsoever that should work

robust condor
#

Bruh, you have update calls on all your methods

drowsy oriole
#

Oh wait thats not supposed to be there.

robust condor
#

You should do the unity tutorials

short hazel
#

All Update methods except the one on line 49 won't get called by Unity

fluid remnant
short hazel
#

This code does almost no action

drowsy oriole
#

I messed up rq I'm fixing

slender nymph
#

"almost no action" is kind of an understatement considering the only line of logic that actually runs is the one line in Start

robust condor
#

This is far from messed up 😄

drowsy oriole
#

I fixed it but It still no work

slender nymph
drowsy oriole
#

yes.

slender nymph
#

alright, why was it wrong

drowsy oriole
#

but it still n work

fluid remnant
drowsy oriole
#

bc I accidently put update in every method

slender nymph
#

that's not why it was wrong, that was what you did. why was that wrong.

drowsy oriole
#

I thought that was why it was wrong

drowsy oriole
slender nymph
fluid remnant
north merlin
#

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(); }

vague sequoia
#

Why does it get stuck when going up the stairs? It's like it's stuck to the wall

slender nymph
#

!code

eternal falconBOT
north merlin
north merlin
#

in editor if i set the keycode to 'r' it works but if i set it to '1' it doesnt

slender nymph
#

just to confirm, you are pressing the 1 key in the number row above the letters, right?

north merlin
#

yes

vague sequoia
slender nymph
# north merlin yes

and you don't have some stupid keyboard that requires some other key combination for that to actually be considered the 1 key, right?

north merlin
#

nope

#

i wrote out the keycode in the script above and it works

drowsy oriole
fluid remnant
fluid remnant
drowsy oriole
#

No, the player still isn't moving

fluid remnant
#

like what does the bool do, sorry

north merlin
#

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

fluid remnant
wintry quarry
north merlin
#

yes

fluid remnant
#

default for AddForce i think is acceleration

north merlin
#

@drowsy oriole did u make a physics material and apply it to ur rigidbody

slender nymph
drowsy oriole
fluid remnant
wintry quarry
hot laurel
#

this blinded ne

north merlin
#

lol

queen cosmos
#

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 = "";
        }
    }
fluid remnant
wintry quarry
drowsy oriole
fluid remnant
slender nymph
#

it's right there in the docs for the AddForce method

fluid remnant
#

oh shoot you're right they are using 2D

drowsy oriole
#

And as a question how would I add a holding button?

fluid remnant
drowsy oriole
#

Like this?

fluid remnant
#

maybe enable a bool on Click n disable it on release then use FixedUpdate to move based on those bools

drowsy oriole
slender nymph
#

there are dozens of tutorials for on screen controls you could be following

fluid remnant
#

PointerDown i think is one frame but you can use that to do the bool thing

north merlin
slender nymph
#

it was set to alpha1 in your screenshots though 🤔

north merlin
#

you're right. Meh unity

#

it works now

amber glen
#

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.

ionic tartan
#

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

slender nymph
#

not a code issue

wintry quarry
#

and upgrade all packages

slender nymph
#

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

ionic tartan
#

ok i will try

ionic tartan
slender nymph
#

if the issue persists after that then close the editor, delete library folder, and launch project again

ionic tartan
#

eh yes

ionic tartan
slender nymph
#

yes

wintry quarry
slender nymph
# ionic tartan

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

ionic tartan
#

Okayy

ionic tartan
north kiln
#

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

ionic tartan
#

so i need to uninstall post processinf package ?

near wadi
#

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.
near wadi
wintry quarry
ionic tartan
ionic tartan
#

hoo i'm so dumb

near wadi
north kiln
#

What IDE?

wintry quarry
north kiln
#

is what I'd use (not sure what the shortcut is for you)

tawny grove
#

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

near wadi
#

i keep getting this, but i will mention here when i figure it out
Cannot navigate to the symbol under the caret.

north kiln
#

Select the thing you want to interrogate

wintry quarry
tawny grove
wintry quarry
near wadi
#

i start by going here
Which leads me to the second image
which then leads me here

wintry quarry
#

PS make sure you have this set to Pivot

wintry quarry
tawny grove
#

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)

near wadi
#

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

wintry quarry
tawny grove
wintry quarry
#

You placed the tiles where they are placed

#

you can of course move the tiles if you wish

near wadi
# near wadi almost like it cannot decompile the dll, but i am sure it can access that info. ...

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
cloud matrix
near wadi
#

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

wintry quarry
#

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

cloud matrix
#

alright ill check now

wintry quarry
cloud matrix
#

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

wintry quarry
cloud matrix
#

it changes the actual prefab and not the one in the scene

wintry quarry
wintry quarry
#

instead of the one in the scene

cloud matrix
#

but it doesnt let me reference the onein the scene for some reason

wintry quarry
cloud matrix
#

ohh

#

is there a way to get around that? like can i spawn the image prefab in afterwards?

wintry quarry
cloud matrix
#

thank you

rocky canyon
#

what do i need to do here?
is it possible to create new c# script via visualstudio..
it put it in twilight or something this is my Temp/Local AppData folder

forest summit
wintry quarry
hot laurel
forest summit
verbal dome
# forest summit

So you have an error happening. You should have mentioned that already

forest summit
#

yeah im not sure why though

#

i tried to see what it was but it doesnt make sense to me

verbal dome
#

Look at the line it points to

obsidian plaza
#

o wait nvm its on trigger

hot laurel
#

your player rigidbody is missing

wintry quarry
obsidian plaza
#

wheres the script

verbal dome
#

It's clear to me too, just trying to teach them to debug.

forest summit
wintry quarry
#

It's in your player script

wintry quarry
rocky canyon
#

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

hot laurel
#

there are templates to pick so you can pick c# script, or just write the file name manually with .cs extension lol

real falcon
#

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
obsidian plaza
#

am i missing where the target function is being calldd

real falcon
#

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

obsidian plaza
#

so u get debug.log AI EXISTS but not PAIN

real falcon
#

yes

#

I also get AI EXISTS

obsidian plaza
#

log linkedai instead of ai exists?

real falcon
#

ok

#

ooh I see

#

I forgot there was an old disabled script on that object

#

of the same supertype

obsidian plaza
#

ah

real falcon
#

thanks, sorry for being dumb

obsidian plaza
#

lol dw

cloud matrix
#

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?

verbal dome
cloud matrix
#

ooo okay imma use that thanku

verbal dome
#

I believe that VS and VSCode also have that option but yeah I can recommend Rider

cloud matrix
#

WHY IS THE INSTALLER 1.4GB 😭

wintry quarry
#

It's the whole app

#

Well it's maybe a self extracting installer

north kiln
#

My install is like 5GB

cloud matrix
cloud matrix
north kiln
#

Your previous IDE probably just wasn't configured

feral drift
#

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

north kiln
#

Absolutely. DOTS is not easy

feral drift
#

perfect thanks for confirming dude!

cloud matrix
#
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

hot laurel
#

just simple event based system which update the ui according to loaded scene/ game state, by updating UI i mean enabling/disabling crosshair

cloud matrix
#

thanx

verbal dome
#

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

cloud matrix
#

fixed it ty!

fast drift
#

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

slender nymph
#

screenshots for the setup, and see below for how to post !code 👇

eternal falconBOT
slender nymph
fast drift
slender nymph
#

if it is a code question, yes

fast drift
#

Well… i dont know if it is. Im having problem with my game.

slender nymph
#

okay well you haven't even said what you're having trouble with

cosmic dagger
#

you should be able to describe the problem. it has to fit under a category: art, unity editor, code (programming), etc . . .

fast drift
#

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:

  1. Collider Settings Checks
  2. 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.
slender nymph
#

we don't need an entire novel about your issue. just a description about what you are having trouble with and the relevant details

fast drift
#

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.

slender nymph
#

you didn't need to rephrase what you've already said. just show the relevant code and setup

cosmic dagger
#

how do you check for a game over? can you show that code?

#

also, the code for the contact with the food object . . .

fast drift
#

I also have console logs if you think it will help

hot laurel
#

'StartCoroutine(AddSegmentWithDelay())' im blind or the implementation of Add Segment is not included here?

fast drift
cloud matrix
#

!ide

eternal falconBOT
hot laurel
#

If you have problem with a segment triggering unintendent game over it would be natural and logical to include the code without a request

fast drift
#

In hindsight, you are right

hot laurel
#

so it triggers the collider

patent verge
#

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

hot laurel
fast drift
#

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

sand dagger
#

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

torn marlin
#

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?

near wadi
#

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

torn marlin
wintry quarry
sand dagger
#

That makes sense

sand dagger
#

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
wintry quarry
#

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

sand dagger
#

So just have that be 0?

wintry quarry
#

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

sand dagger
#

Ok well that was why I had to put like 500 just to move at any decent speed

sand dagger
wintry quarry
#
Vector3 right = transform.right * horizontal * horizontalSpeed;
Vector3 forward = transform.forward * forwardSpeed;
body.velocity = right + forward;```
#

something like this

sand dagger
#

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

echo kite
#

how do i add models from my pc

#

fbx file

hot laurel
#

drag and drop to unity Project window?

echo kite
#

ok

burnt vapor
echo kite
#

ok sorry

lean basin
# torn marlin Is it recommended for a programmer to use code for doing everything even assigni...

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.

tough plinth
#

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....

  1. It creates thousands of clones in the hierarchy window even with a bool statement which should break the loop.

  2. VFX does not emmit (no confetti)

wintry quarry
patent verge
#

can I test the player light level and convert it to a value?

tough plinth
wintry quarry
eternal falconBOT
tough plinth
#

Oh

wintry quarry
#

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

tough plinth
#

I set collected = true; but due to being in a different block, it's not being changed?

wintry quarry
#

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

wintry quarry
#

it's just a local variable

tough plinth
#

Oh

wintry quarry
#

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

tough plinth
#

So.. If I say:

bool collected = true;

It will be changed to a public variable? And it won't disappear?

wintry quarry
#

no

#

"public" is not relevant here

#

what is relevant is the scope of your variable

#

and where and when you assign values to it

tough plinth
#

Isn't public like making turning it off "invisible" so entire script can access it?

wintry quarry
#

no

#

not at all

#

you are confused

#

Forget about public

#

that's not important here

tough plinth
#

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

wintry quarry
#

you need to worry about the difference between:

  • A local variable
    and
  • A member variable / instance variable
wintry quarry
#

forget all of that, it is wrong.

tough plinth
#

Alright alright

wintry quarry
#

public and private is not relevant to our discussion at all

#

that's for something else entirely.

wintry quarry
tough plinth
#

I got it

wintry quarry
#
public class Example {
  int memberVariable = 6;
  
  void SomeFunction() {
     int localVariable = 4;
  }
}```
#

This is what we are worried about

#

You have a local variable

tough plinth
#

Yeah

wintry quarry
#

You probably want a member variable

tough plinth
#

Is it that one on the top?

wintry quarry
#

the one called member variable of course

tough plinth
#

because void is like. nothing

wintry quarry
#

void isn't important here

#

that's just the return type on the method

tough plinth
#

A okay

wintry quarry
#

I'm talking about the two variables in the example

#

the ints

tough plinth
#

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

wintry quarry
#

you're not understanding what I'm saying

#

I never said to do that

#

Why would you do that

tough plinth
#

I don't

wintry quarry
#

Your problem is that collected is a local variable

#

you need to make collected a member variable

tough plinth
#

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

wintry quarry
#

if it's a member it becomes part of the script

tough plinth
#

I'm confused

wintry quarry
#

it lives as long as the script does

#

(which usually lives as long as the GameObject it's attached to)

tough plinth
#

Yeah

wintry quarry
#

So you need to store it somewhere that survives across frames

#

such as on the script itself.

tough plinth
#

Yep

wintry quarry
#

A local variable only lives as long as the function takes to execute

#

usually a few nanoseconds

#

and then poof it's gone

tough plinth
#

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

wintry quarry
#

basically local variables are for temporary storage inside a function to facilitate the function, that's it.

wintry quarry
tough plinth
wintry quarry
#

really "at the top" isn't as important as "inside the class, but not inside any function"

cloud matrix
#

I've never seen the $ before a debug, what does it do?

wintry quarry
#

In this particular case it doesn't do anything

#

You would do something like:

Debug.Log($"There are {_playersAlive} players left alive");```
cloud matrix
#

ohh okay good to know

wintry quarry
#

and that will print the current number of players alive (or whatever is stored in that variable)

cloud matrix
#

ohh right

wintry quarry
#

It's kind of a nicer way of writing:

Debug.Log("There are " + _playersAlive + " players left alive");```
cloud matrix
#

good to know for the future, thanks :)

tough plinth
#

You said inside the class, so I can place that line everywhere (but not in Update and Start and so on)

wintry quarry
#

Not that I would recommend it

#

but yes

tough plinth
#

And as you said, inside the class, but not in the function, else it will be a private variable

wintry quarry
#

not private

#

local

#

private is a different thing entirely

tough plinth
tough plinth
#

alright

wintry quarry
#

It's up to you, but convention is typically at the top of the class, yeah

tough plinth
#

Sometimes people but some declarations in void Start() why?

#

Isn't everything before Start() being executed as well?

wintry quarry
keen owl
tough plinth
#

Oh yeah, that's what I saw

tough plinth
#

Or it's like
"Just once and forever"?

keen owl
#

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

tough plinth
#

Oh alright

#

Thanks with that!

wintry quarry
#

No GetComponent outside

tough plinth
#

Ohh

#

wait you really can't?

wintry quarry
#

you really can't.

tough plinth
#

No errors, why

keen owl
#

It’s being called inside a method

tough plinth
#

private void OnCollisionEnter is a method?

keen owl
#

Yes

wintry quarry
tough plinth
#

Sorry if that's a dumb questions, I'm really new to unity

hot laurel
#

its not about unity

wintry quarry
#

method and function basically mean the same thing, by the way

#

you can use them interchangeably

tough plinth
#

Functions are more familiar to me, so I'mma try to remember 2 meanings okii

keen owl
#

They’re usually referred to methods in C# because of the language’s encapsulation overall but in C/C++ they’re referred to functions

wintry quarry
#

"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.

tough plinth
#

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)

wintry quarry
#

otherwise you can call Play() on it

tough plinth
#

It does copy, but it does not emmit anything, is there a key difference between EmptyParent game object and original game object?

wintry quarry
#

(or more advanced, set up your own events)

tough plinth
#

Maybe that's why

#

Yayyy!! It works!!!! Tyyyyy guyss

brittle maple
#

(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.

burnt vapor
#

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

brittle maple
#

Never used Intercaes btw, so I will have to learn...

burnt vapor
#

For example, if your Door were destructible you'd be able to add an IDestructible interface

burnt vapor
brittle maple
#

Thanks!!

burnt vapor
#

Feel free to ask once you have a general understanding

echo kite
#

why does it give 300 ammo after i reload if clips are 30

languid spire
eternal falconBOT
echo kite
#

'''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;
}

}
'''

echo kite
#

and i havent been told

naive pawn
#

Surround code with three backquotes. Not quotation marks.

languid spire
echo kite
#
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;
    }
}
burnt vapor
#

This is what would be considered a large code block

languid spire
#
_currentAmmoInClip += _ammoInReserve;

should be amountNeeded

naive pawn
#

also the entire tree could just use Mathf.Min

#

anyways what's with the >-

echo kite
languid spire
#

what? Now you can post a screenshot

echo kite
#

i changed >-

#

too

languid spire
#

why the_ ?

naive pawn
#

it's amountNeeded, not _amountNeeded

echo kite
#

ok

naive pawn
#
reloadamount = min(clipSize - clipCount, reserve)
clipCount += reloadAmount
reserve -= reloadAmount
echo kite
#

it works ty

vocal urchin
#

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.

rough hill
obsidian plaza
#

cause there is constraintCount

vocal urchin
# obsidian plaza

its doing its own thing. But now I've found out about unity's navigation system 😮

molten robin
#

is there any noticeable difference between Lerping in FixedUpdate and Update?

rich ice
#

typically you'd want to put it in update though, unless you're lerping something physics based, like velocity

charred spoke
#

I would say the difference would be the same as the general difference of frequency between Update and FixedUpdate

burnt vapor
#

It would be less smooth

#

I don't see why you'd use it in FixedUpdate

#

Lerp is not physics related

charred spoke
#

Unless your framerate dips

rich ice
#

^ plus1

burnt vapor
#

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

charred spoke
#

This is also true

#

It’s why delta time exists

vocal urchin
#

wow

#

the navigation system rules

twin scroll
#

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?

rich ice
#

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

left oak
#

whenever i download it and try to upload it to itch.io it says filename not found

green flame
#

Hello! Is there a way to add a custom ID to a new VisualElement created with C# ?

languid spire
languid spire
green flame
#

I'm too much in web logic, I searched for something like "attribute.id" etc.. ^^

fleet surge
#

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

naive pawn
#

also consider setting a float and doing the logic in the animator

north kiln
fleet surge
naive pawn
#

open the settings menu

#

also that isn't a trigger, that's a different kind of parameter

naive pawn
#

yeah just clarifying since you named it trig and also mentioned a trigger

#

you don't have any triggers there

fleet surge
#

yep I'm aware, I'm just using a naming convention that's easier for the way my brain is wired lol

naive pawn
#

aight lol

frail wind
#

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.
frail hawk
#

better use an ui image with fill type

frail wind
frail hawk
#

sorry what

wintry quarry
hexed terrace
frail wind
#

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).

dim yew
#

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

naive pawn
#

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

dim yew
#

it would likely be very interconnected

#

is it much more optimized to use multiple?

#

or is that just for ease of use depending

hexed terrace
#

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/

dim yew
#

cheers

obsidian plaza
#

$35 paperback and $25 ebook.. how big is this book

#

is that normal

hexed terrace
#

or read it online for free, scroll down

wintry quarry
#

Sounds pretty standard for a book

obsidian plaza
#

ah ok i see thanks

rich adder
rich adder
#

@echo copper !code 🔽

eternal falconBOT
echo copper
#

urm... im sorry, i don't get this...

#

ow

rich adder
#

whats not to get?

#

put the code on the site, save and send link

echo copper
#

ow, ok

#

code of sonic

#

code of rays

rich adder
#

btw you can format links to have title by using markdown
[link-label here](url)

echo copper
#

ok

rich adder
echo copper
#

these points under sonic are points where ray collides with ground

rich adder
#

ohso you want it to move along the slope ?

echo copper
#

yes. that's what sonic physics based on

rich adder
#

shouldn't you be using something like V3.Project or ProjectPlane ?

#

trig is my weakness sry

echo copper
#

no..?

echo copper
rich adder
#

cause I don't see anywhere in your code using normal of the thing you hit

echo copper
#

no, he should find the angle between points, not the normal of ground

#

but i can try these v3project or projectplane

rich adder
#

Oh I guess I use it for CC and its different, i use Normal for slopes and other calcs like that

echo copper
#

so, you are recommending me to use normal, right?

verbal dome
rich adder
#

Idk I just saying I use that to get the angles, you don't have to

verbal dome
echo copper
rich adder
#

even still move the RB.MovePosition for accurate collider simulation

echo copper
#

urm... what?

rich adder
#

this gives other physics objects more accurate collider/physics hits from this kinematic body

echo copper
#

sonic don't even moves

rich adder
# echo copper it don't even move

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

echo copper
#

ow, sry, just wrote code incorect

#

but sonic still don't move along the slopes

rich adder
#

It wont fix the slope issue but its just something you should consider doing regardless lol

echo copper
#

ok, so should i try normal?

rich adder
#

yeah like Vector3 slopeDirection = Vector3.ProjectOnPlane(moveDirection, hit.normal); something like that

echo copper
#

in ray code or in sonic code?

rich adder
#

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.

echo copper
#

okay, thanks. It looks workable

rich adder
#

I try to use these methods more cause my trig is not very good lol yes gamedev its all over the place

ashen frigate
rich adder
echo copper
#

i understand ya

ashen frigate
#

tnx

rich adder
hallow bough
#

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 )

rich adder
#

you talking about the accelerometers ?

#

if so look like it even has an API for c#

short hazel
#

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

rich adder
#

just a fancy name for an encoder then

echo copper
hallow bough
naive pawn
ivory bobcat
echo copper
rich adder
rich adder
hallow bough
rich adder
#

this thing doesnt find normals, it just spits out a direction

rich adder
#

I see you should get back some floats

#

you can def use that to navigate menus

hallow bough
rich adder
#

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

hallow bough
rich adder
#

don't worry about that

#

whats important is you're working with a float value

#

forget the hardware for now

hallow bough
ornate aurora
#

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?

rich adder
#

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

hallow bough
#

ty. I will try to figure it out form here. Can I dm you if I have any more questions?

naive pawn
#

just ask here

rich adder
#

I'm learning just like you

lapis halo
#

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

lapis halo
#

yes

#

thank you

rich adder
#

makes you write code as if you were in Vm

west radish
#

why do keyboards actually come with an insert key?

rich adder
#

for that reason

#

its for that old style

west radish
#

yeah, but it has to be a very small percentage of people who really make use of it

rich adder
#

Yeah I think it just helped people transition easier

#

no clue lol

naive pawn
#

i use it as a hotkey for leaving discord calls

rich adder
#

I have a 60 so its a pain to even enable it lol

west radish
#

60 what?

rich adder
#

keyboard 60%

west radish
#

ooohh

naive pawn
#

wow come to think of it my discord keybinds are all pretty weird

west radish
#

I used to have a foot pedal that I used for push to talk

rich adder
#

my led lights up the primary keys but not the fn shortucts thinksmart

naive pawn
#

rate my keybinds

ornate aurora
# ornate aurora Hi! I want to make an infinite tilemap for my 2D game. I already managed to gene...

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.

rich adder
ornate aurora
#

Yes I read about those optimizations, but there were some cons on updating the tilemap

rich adder
#

if each gameobject is just a static tile that doesnt do much you might incurr more bottleneck if they are all gameobjects

rich adder
#

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)

obsidian plaza
ornate aurora
#

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

azure bridge
#

hello guys hlep

#

i need help w my script cause my bunny is moving weird

#

i can stream or record

wintry quarry