#archived-code-general

1 messages ยท Page 165 of 1

lean sail
narrow blade
fluid juniper
#

Not sure if this is the best channel for this, but it does include code so I will post it here. I have a simple player controller in a 2.5d demo game. When using the "Windows, Mac, Linux" build preset, everything works fine. However, when switching over to the WebGL build preset, the player continues moving for a second or two after the key is released. Does anyone know what could be causing this? I have attached the code, a video of the issue, and a screenshot of the components attached to the Player GameObject. Thank you for any help that you can provide.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Example : MonoBehaviour
{
    private CharacterController controller;
    private Vector3 playerVelocity;
    private bool groundedPlayer;
    public float playerSpeed = 2.0f;
    private float jumpHeight = 1.0f;
    private float gravityValue = -9.81f;

    private void Start()
    {
        controller = GetComponent<CharacterController>();
    }

    void Update()
    {
        groundedPlayer = controller.isGrounded;
        if (groundedPlayer && playerVelocity.y < 0)
        {
            playerVelocity.y = 0f;
        }

        Vector3 move = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical")).normalized;
        controller.Move(move * Time.deltaTime * playerSpeed);

        // Changes the height position of the player..
        if (Input.GetButtonDown("Jump") && groundedPlayer)
        {
            playerVelocity.y += Mathf.Sqrt(jumpHeight * -3.0f * gravityValue);
        }

        playerVelocity.y += gravityValue * Time.deltaTime;
        controller.Move(playerVelocity * Time.deltaTime);
    }
}
#

Never mind, figured it out. I think that the character controller physics are designed to have it gradually slow down, however normalizg the movement vector caused the magnitude to always be 1 (even when it should have been lower to slow down). Adding a simple if statement that only normalized the input if the original magnitude of the vector is greater than or equal to one seems to have solved the problem.

hidden parrot
#

Hey guys, just looking for some help with an implementation here.
So I've got inventory items that all implement an interface IEquippableItem, which has methods like OnFireKeyStart, OnFireKeyEnd, OnReloadKeyPressed, etc.
My problem is saving. Because the inventory system stores a variable of IEquippableItem for its selected item, I can't serialize and save it. What I've done is create a Dictionary<string, IEquippableItem, then save the string with a dumb search method to find the string from its value, and load the item based on its string value.

I don't think this is the optimal solution, and it definitely isn't considering I want to be able to save item data too. Any suggestions?
I was considering adding an OnSave method which returns a string of all the data that gets serialized, but I'm curious if there are any other ideas.

#

(By "item data" I mean data for individual implementations of IEquippableItem, for example a firearm implementation might want to save its current ammo and other stats, while a medkit might want to save use count)

lean sail
hidden parrot
lean sail
#

i wouldnt save every single item, you can represent all of them in like an SO. In terms of the null variables, are you really gonna have that much difference between them? A few variables that get ignored really arent an issue

hidden parrot
lean sail
#

you might have an easier time just creating a struct/class for different types of objects then, because at least then you'll be able to easily deserialize it. Serializing is easy, you can literally just write an anonymous type
new { x = something, y = somethingElse }
call JsonConvert.SerializeObject on it, and WriteAllText it (assuming you're using json).
the annoying part is just getting the data out without having an exact data structure for it

hidden parrot
#

Alright, I'll try it out. Thanks for the help

undone grove
#

qq: is there best practices for how to handle Steam failing to init from Facepunch.Steamworks? Would it be acceptable just to quit the app as bare bones drm?

lean sail
bright orbit
#

Hello, I'm having issue with the following code. https://gdl.space/ecojezinon.cs

The code is for controlling a 2D character and I'm attempting to run a coroutine that makes the character "ground pound". The intention is to check if the character is on the ground and, if he isn't, allow the player to press "S" to initiate a ground pound which holds the character in the air for 1 second before moving him downward quickly until he is grounded again. When trying to execute the code, the character will hang in the air but then the game will freeze once it attempts to start the downward movement. I've whittled it down to the "while (IsGrounded()==false)" command as the culprit of the crash but I'm unsure on why this won't work as programmed.

hidden flicker
#

How do I get the value of a custom variable that I've assigned to a gameobject

lethal minnow
#

I am trying to run a script so that if a room is placed in a green square, the red one will run a method to recompute its walls. How do I make it so that when a user places the green room, all adjacent rooms will run a method?

lethal minnow
#

fromObjectClassName would be the script fromObject is using that stores the variable you are using

rigid island
lethal minnow
rigid island
#

nodes and such

#

check if tiles / nodes are occupied

hidden flicker
#

like that

rigid island
hidden flicker
#

ah, ok

lethal minnow
rigid island
#

btw 1 unity unit = 1m

lethal minnow
rigid island
#

do the neighboor checking and run methods on them

lethal minnow
#

I have ways to know if there are methods I just don't know how to get the neighbors to run the methods after I detect them

mild osprey
#

I'm getting a weird issue when using a lerping value as a variable. returnSpeed has a value of ten and returnSpeedP is just a constantly decreasing value. When I enter returnSpeed as the variable multiplied by deltaTime (highlighted yellow), I get no errors and it works as intended, but when I enter the lerping returnSpeedP I get errors saying the Quaternion is a null value (NaN, NaN, NaN, NaN). Not sure why this happens and I can't seem to find anything about it online.

rigid island
#

make it a bool one and set occupied true for all filled tiles

#

dictionary would probably work too tbh

spring creek
#

Oh, yeah and they are setting back to the same variable

spring creek
#

Lerp(a, b, fraction)

mild osprey
#

okay I see

#

Is there a way to lerp at a changing rate?

#

because doesn't deltaTime already change?

spring creek
mild osprey
#

So multiplying the time parameter wouldn't work? Would I have to change the parameter itself's value?

pure cliff
spring creek
#

Are targetRot and currentRot set earlier? How?

mild osprey
#

Yes, they are set by some sin functions earlier in the code

#

The code runs perfectly fine when just deltaTime, it's only when I'm using the lerping value do the quaternions throw a fit

spring creek
#

Then it may be about setting the same value as the first parameter. Like targetRot is the variable you store lerp in, but also the a parameter

#

Quaternions are really tricky. I have to look into that more

mild osprey
#

Yeah I've been trying to figure them out as well, I came upon this potential solution becuase you can't really easily subtract quaternions so I'm using this method as a workaround

#

you can add by the inverse of a quaternion for subtraction but it's still funky

spring creek
#

Yeah, I am not sure what is going on. Sorry.

mild osprey
#

S'all good, I see if the unity forums have any wisdom, or i'll just bump this later.

lethal minnow
rain minnow
mild osprey
#

Yeah I know it's weird and I know it's usually not recommended. I agree, but I'm using it as an easing function that never needs to hit it's target value

real scarab
#

is there a better way to wait an amount of time then

timeelapsed += Time.deltaTime;
if (timeelapsed > 2f) 
{
// do action
}
#

specifically in the update function not in other functions

prime sinew
#

Is there something in this you're wanting to avoid?

real scarab
#

not specifically, I just try to avoid if statements and nested code where I can

prime sinew
#

I would've suggested a coroutine but you wanted it to not be another function

real scarab
prime sinew
soft shard
# real scarab is there a better way to wait an amount of time then ```csharp timeelapsed += Ti...

In general there is nothing wrong with using if-statements, there are probably other ways you could change the readability, though if you wanted to remove the "+=" deltatime logic, you could make the time you want to wait a variable and use Time.time instead to check for a difference, this will tell you the time since the scene loaded, for example:

if (Time.time < timePassed) {return;}
DoSomehingInteresting();
timeePassed = Time.time + someWaitTime;

I use this approach often, to exit if there is still a cooldown, otherwise do the logic and add some value to the time to wait in the future, you could even have a "remaining time" for some UI by subtracting the Time.time from timePassed if you wanted

real scarab
#

Thank you both so much!!

lean sail
#

writing the logic of an if statement on the same line is ๐Ÿคข imo

soft shard
#

Understandable, I personally like using one-liners if the logic inside { } is basically just a single keyword (I do the same if a property is only a get;set;), and it looks more compact on Discods codeblock, but I also understand not everybody likes one-liners lol

lean sail
#

whenever i see stuff like that, i just assume the person wrote it to save on line count. For some reason people thinks it matters

soft shard
#

Its all personal preference imo, some programmers I know like

if (condition){
}

Others

if (condition)
{
}

And some

if (condition){}

They all do the same thing, though I find the first are often preferred by programmers I know with a JS or web level background, imo it just looks odd having only 1 short line in between brackets more than "lines cost too much so save on them"

real scarab
lean sail
lean sail
#

So it just doesnt really make sense when you could just do

if(condition)
  something

in all cases

real scarab
#

ya I can see that especially for a team of multiple people

soft shard
#

Thats a good point, and yes on a team project its best to go with whatever convention the codebase is using, on solo projects its fine to go with whatever your preference is, I personally always like seeing the { } on any if-statement even if its not on one line, in my mind it makes it more clear what logic is meant to be grouped together, but thats entirely a personal thing for me

real scarab
#

I also bet alot of people who started with python really prefer options 1 & 2 seeing as one line if statements are mostly impossible

rain minnow
#

for me it's . . .```cs
// C++
if () {
}

// C#
if ()
{
}

// Return or one-liner here.
if () { return; }

leaden solstice
#

Heretics

fervent furnace
#

I prefer if(){
}
In no matter what languages

quartz folio
#

I follow the C# standards except I use tabs not spaces (spaces are truly cursed and I will never understand their reasoning)

lethal minnow
opal sand
#

does anyone know why my intelliSense isn't working even though i have the C# extension enabled?

fervent furnace
#

vscode?

opal sand
#

yea

#

idk im new to unity

quartz folio
#

!vscode

tawny elkBOT
#
Visual Studio Code guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

https://on.unity.com/vscode

opal sand
#

no theres no endless spinning

#

at least based on what i see

earnest gazelle
#

Have you used C# observable collections or custom one? to update for example a list based on changes data

lime niche
#

Whats a good way of checking if the player is looking left or right in a first person 3D environment ?

#

Mouse delta does not work very well.

prime sinew
lime niche
fervent furnace
#

how do you define direction? eg head and body are two different transform you define the forward as body.transform.forward, then your problem is solved

orchid bane
#

Can I create an editor like UI in game? I want to add a tool for creating some data and there will be lists of values, is there a convenient way to add the dropdowns and + and - buttons? Possibly with my own textures?

lime niche
#

I'm using the input system and adding to move dir and multiplying it by the force

#
 Movedirrelative = orientation.forward * movedir.z + orientation.right * movedir.x;```
#
  rb.AddForce(Movedirrelative.normalized * Force * 10f, ForceMode.Force);```
prime sinew
pure cliff
# lean sail whenever i see stuff like that, i just assume the person wrote it to save on lin...

So the funny thing about this BTW is, once upon a time it did, and still does in specific niche areas.

Namely, there is a practice of printing code off on paper for code reviews for security / protocol reasons.

IIRC, NASA still does this, and some other places where human lives depend on code. You can look up NASAs code standards documentation, they have a big list of "must do"s and "never do"s, it's actually quite fascinating haha

lime niche
scarlet viper
#

is package manager lagging now ?

#

or is it just me ?

soft shard
mellow zinc
#

Can Anybody help

#

if (allowButtonHold) shooting = Input.GetKey(KeyCode.Mouse0);
m_ShootingSound.Play();

    else shooting = Input.GetKeyDown(KeyCode.Mouse0);
#

This code

#

has an error

#

it says that 'else' cannot start a statement

#

how do i make it play the shooting sound when i click mouse0?

gray thunder
#

This is why we use {}

#

Please for the love of god encapsulate

#
if()
{

}
else
{

}

@mellow zinc

orchid bane
rocky helm
#

How do I loop through polygons on a mesh?

undone jay
#

I dont really know how to word this since im fairly new but i have the enemy object on the left that keeps getting stuck where i drew the red arrow. itll keep running into it unless i move the player in a different direction. Does anyone know a fix or how i can make it repath or something.

mental rover
rocky helm
#

like if i wanted to loop through each of these faces/polygons, can I do that?

#

they are all flat

shy knoll
#

help when i walk left the player doesnt look too the left

        Vector2 moveDirection = new Vector2(horizontalInput * speed, rb.velocity.y);
        rb.velocity = moveDirection;```
soft shard
# orchid bane Canvas system, players add some things to their game, not sure what you mean by ...

Ah I see, ill give you an example of what I meant by data binding, maybe it could give you some ideas - for one project I wanted to make it easier for our designer to generate and edit Scriptable Object (SO) files in a build, essentially using the SO to have UI fill a resizable "container" with rows of prefabs setup for certain data fields (like a "int row" for numbers, "text row" for strings, "dropdown row" for enums, etc), changing data of those rows, are bound to set the value of the SO, or JSON file or any other approach, this could be useful if you need to save/load this data back into Unity or maybe through a "workshop" server, but if this is just for a session or to sync over multiplayer, maybe data binding isnt very useful

Creating character configs sounds like you could largely edit/create JSON files from a serialized class, and maybe take a similar approach to looping through data types to generate prefab "row types", then instead of binding the data, store it in a class instance and create a new file or overwrite an existing file with that instance - is this what you might be looking to do?

rocky helm
shy knoll
rocky helm
#

is it a 2d game

shy knoll
#

yes

rocky helm
#

then you rotate the player left or right, depending on the velocity

#

whenever the player moves

shy knoll
#

how is my question

#

i dont know how so i came here

rocky helm
#
private void Move(){
  horizontalInput = Input.GetAxis("Horizontal"); // Left Stick
  Vector2 moveDirection = new Vector2(horizontalInput * speed, rb.velocity.y);
  rb.velocity = moveDirection;
  if(horizontalInput < 0){
    //rotate player left with either using another image of the player or somehow mirror the image, idk I haven't done anything 2d
  }
  else{
    //rotate player right
  }
}
shy knoll
#

thanks

rocky helm
#

since I need to loop through every polygon on a mesh and convert the polygon to a ConvexPolygon2D

soft shard
# rocky helm Does anyone know how/if I can loop through every polygon/face?

Im not sure if theres a built-in utility API or something, you could maybe checkout a video on "mesh generation", CodeMonkey I know has a good one, AFAIK, the mesh only has verts, so you would have to group those verts into what you would define as a "face" within that collection of verts, I think TextMeshPro uses something similar to group individual characters from vert data, though that goes above my head

mental rover
swift falcon
#

Is there any way at all to make methods that don't belong to any object or class? I'm not 100% against making a dummy wrapper class, but I don't really want to unless I have to.

Not sure if it makes a difference but I wanted to have a dictionary with delegate as the value type, so the methods could be invoked by anything with access to the dictionary, so for that reason having the methods belong to anything doesn't really seem necessary to me.

rocky helm
#

like if 4 edges make up a face/polygon, can I detect that?

#

god dammit I suck at describing my ideas

frigid hedge
#

hello, is there a channel wher i can get helped?

rocky helm
#

yes

frigid hedge
#

oh, where?

rocky helm
#

depends on what kind of help you need

frigid hedge
#

i need help with unity, literally. i dont know how to turn a 2d object to a photo

swift falcon
mental rover
rocky helm
mental rover
#

I'd look into what blender can do for you first if you have access to it personally

frigid hedge
#

could someone help me pelase?

rocky helm
frigid hedge
#

ok thanks ๐Ÿ˜„

swift falcon
#

which is obv less than ideal

rocky helm
# swift falcon yeah i feel like that would be hard, i was dealing w/ a similar problem and it s...

I mean, I am trying to make what was explained in this video https://www.youtube.com/watch?v=nuHg6_IIyK8 (important parts are 0:30-0:35 and 1:00 to 1:15). They make it sound so easy and I feel like there is an easy-ish solution to this

In this video, David shows you how we made the glass breaking effect in Receiver 2.

โ€ข Get Receiver 2 - https://store.steampowered.com/app/1129310/Receiver_2/
โ€ข Discord - https://discord.gg/Wolfire
โ€ข Reddit - http://www.reddit.com/r/Receiver
โ€ข Instagram - https://www.instagram.com/WolfireGram
โ€ข Twitter - http://www.twitter.com/Wolfire
โ€ข Facebook...

โ–ถ Play video
rocky helm
# swift falcon yeah i feel like that would be hard, i was dealing w/ a similar problem and it s...

I the video at around 1:05 he says that he broke the polygons down into triangles and extruded them back as 3d models, but before that he needed to cut away the part of the fracture pattern that extended out of the bound of the glass. That is the thing I'm trying to create right now, to cut off the part that extends too far. But for that I need to maintain them as polygons right? since if I did it with triangles then I couldn't really put the remaining parts back together right?

mellow zinc
#

does anybody know how to make gun audio with a raycast shooting script

mental rover
#

split the mesh to solve your original problem immediately perhaps

rocky helm
#

The only workaround I can think of is to make every face into separate objects, but that is clearly not what was done in the video

rocky helm
swift falcon
#

you're right, he does make it sound really easy, and just gives like 0 insight into it LMFAO

#

my geometry chops are weak tho

soft shard
# mellow zinc does anybody know how to make gun audio with a raycast shooting script

Your question might be a bit unclear, audio and raycasts are completely independent systems, so you cant really make a raycast play audio, but you can play audio in response to calculating something about the raycast (assuming you have an AudioSource you want to use) - what is it specifically that you are trying to do? Are you trying to play audio at the point a raycast hit say a wall or crate or floor tile? Or are you trying to play a "bang" sound every time your weapon is fired? Or are you trying to do something else in specific?

mellow zinc
#

Im trying to make a shooting sound when the weapon is fired

#

I've searched up tutorial and they say to include it under my script where I have Input.GetKeyDown(KeyCode.Mouse0);

#

But I dont have that and I can't find where the script tells the gun to shoot

soft shard
# mellow zinc But I dont have that and I can't find where the script tells the gun to shoot

Generally when your shoot logic fires off (from input or an event or some other way), that is a good place to handle playing audio, but does depend on you Input solution and code setup (for example, are you using the Input class and KeyCode enum, or the "new" Input package?) - did you write this script yourself or followed a tutorial or copied it from somewhere online? Could you also show the full script? You can use a code pasting site like pastebin, hastebin, pastemyst, etc

mellow zinc
soft shard
mellow zinc
#

how would i do that

soft shard
mellow zinc
#

yes

#

would it be public

#

then audio source

#

and then i give it a name

soft shard
#

Generally, yes a variable or reference is <access> <type> <name>, in your case public is the "access" and AudioSource is the "type", the name can be whatever youd like (within reason of syntax), though how familiar are you with C#? Specifically, how much of this script do you currently understand what its doing?

mellow zinc
#

Im empty on C#

soft shard
# mellow zinc Im empty on C#

Ah I see, personally I would maybe start with C# basics tutorials first (with Console applications or maybe even WinForms if you prefer visual learning), before hopping into Unity, mostly because the engine itself, has a lot of "syntax sugar" and can be confusing building a game with only relying on tutorials for super specific things (like "how to make a gun"), if youd like a good understanding of the engine "Unity Learn" may be a better starting point imo than specific tutorials, so you get to learn a good understanding of the basics of how everything from simple to complex is generally structured, then tweak that to your specific preferences

mellow zinc
#

like completed them

soft shard
# mellow zinc like completed them

Did you understand the code and the projects you completed? Or just went through the steps they outlined mostly cause the tutorials said to do x step next?

mellow zinc
#

I understood them

soft shard
#

Ah ok, thats good then, if you personally feel that you already have a good understanding of the basics of C# in general, I would continue to go through more of their projects to familiarize yourself with the engine more and maybe refresh on how references and data works in Unity, but also try to understand this script or any script you find, and the reasons why certain code is structured the way it is or why it even exists in x script, that way itll be easier to follow the logic of the script to make small changes to it and eventually write your own unique scripts from the default Mono template (or a blank script file entirely)

mellow zinc
#

ok

#

thanks

soft shard
#

Np, hopefully that helps out with your current problem as well, if not after trying some things, you could try asking again later with all the info we went over in #๐Ÿ’ปโ”ƒcode-beginner for further help, GL

mellow zinc
#

ok

proper olive
#

Hi everyone
I understand it is best to provide a code snippet but i dont have my laptop with myself

Ive been encountering a weird glitch with using Raycasts for wall detection.

I cast two of them for two of the walls and they work fine when above 50 fps but if i drop my fps to sth like 30 fps the wall run starts and stops immediately

Now the weird part is, this only happens with some scenes. If i save my player and level as a prefab and create a new scene everything works fine even at 15fps. If i create another scene the bug has a random chance of appearing

#

And it wont go away

#

I even modified the code with fixeddeltatime but it still happens randomly

#

Its not even consistent

soft shard
# proper olive Hi everyone I understand it is best to provide a code snippet but i dont have my...

I think that kind of problem might need more context, when you are able to access your laptop, it may be good to provide the code your using for raycasting and where you are using it, off the top of my head with the description you gave, it could be many factors, it could be the distance or direction of the cast, the cast could be hitting a internal collider (if the origin is for example, from within your player collider), gravity could play a part or some other factor - you can also use Debug.DrawRay (https://docs.unity3d.com/ScriptReference/Debug.DrawRay.html) or Debug.DrawLine (https://docs.unity3d.com/ScriptReference/Debug.DrawLine.html) if your using a raycast to get a better idea whats going on in the Scene view as you playtest your game, or Vertx has a very nice package to visualize the rest of the Physics class if you are using a shape like a SphereCast or something: https://github.com/vertxxyz/Vertx.Debugging

tawdry jasper
#

Looks like properties of my ScriptableObject aren't serialized. If I add an extra public string on it, I can see it persists, but the data I actually want to use seems to ne wiped on domain reload?
(I have a custom editor window to list what's in the dictionary, WorldLocationType and SceneName are enums)

    ```
Seems like this ^^^won't serialize on a scriptable object?
hexed pecan
#

You can try SerializableDictionary, for example. It is 3rd party

tawdry jasper
#

well... that explains it. nah, I was just confused. Can it do lists? I can build the other stuff on deman it's just for displaying and house keeping at runtime I just need a list really, thank you!

hexed pecan
#

Lists are fine. HashSets not

simple egret
#

You can't mute people because you do not have moderator rights here

#

<@&502884371011731486> Shitposting

#

You agreed to rules entering here, please follow them

#

Your spam here clearly shows otherwise

oblique spoke
#

!ban 1137393118984028301 Shitpost account

tawny elkBOT
#

dynoSuccess johndev0598#0 was banned.

mellow zinc
#

can anybody help, when I start the game my main fps cam just starts slowly going up until a certain point https://hastebin.com/share/ijujizefuh.csharp

simple egret
#

I suspect the line 32 is the culprit

#

You're adding a position each frame

mellow zinc
#

how would i fix that

simple egret
#

There should be only line 31, if I'd guess

mellow zinc
#

so i should delete 32?

simple egret
#

Maybe? The script makes use of multiple positions

#

You should know, you wrote that right?

mellow zinc
#

nope

simple egret
#

Start by writing your own instead of blindly copy-pasting from others, and it'll be better

mellow zinc
#

ok

simple egret
#

If you need tutorials, there's the Unity !learn website

tawny elkBOT
#

๐Ÿง‘โ€๐Ÿซ Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

mellow zinc
#

ok

tawdry jasper
#

What's a good way to debug why the unity editor freezes (I'm on osx, it just spins the beachball and is unresponsive, I can forcequit the app). I'm pretty sure it's my code somehow, but not sure what it is exactly)

simple egret
#

Any infinite loop will cause the editor to freeze. Search for anything that would cause that. for and while loops with flawed exit conditions

#

Attaching the debugger while playing might help, you can pause the execution when frozen, and it'll show you where the code is executing

cobalt gyro
#

what is the Unity namespace used for

#

not UnityEngine or UnityEditor, just Unity

knotty sun
#

there is no Unity namespace

somber nacelle
#

there is actually, pretty sure the AI navigation package is in it

knotty sun
#

Nope, UnityEngine

somber nacelle
#

nope, Unity.AI.Navigation

knotty sun
somber nacelle
#

mate i literally just linked you to what i was referring to

knotty sun
#

and I just screenshotted you what I was refering to

somber nacelle
#

yes and i said the "AI Navigation package" which you said nope to. what you screenshot is the NavMeshAgent which, not surprisingly, is not part of the package i referred to though it is related

dark sparrow
#

How to stop a navmesh agent immediately and put a new destination for it?
It seems like it wants to finsh the last destination before applying the new one using navMesh.destination = position;

somber nacelle
#

call the SetDestination method on it

#

assigning to the destination property doesn't immediately recalculate the path afaik

dark sparrow
#

Yep, that seems to work better, thanks

hollow knoll
#

Hi im making a hunting simulator that works with laser detection like when you shot at the screen with laser catridge a camera detects the laser Place what do i need to get started

knotty sun
#
using System.Collections.Generic;

namespace UnityEngine.AI
{
    [ExecuteInEditMode]
    [DefaultExecutionOrder(-101)]
    [AddComponentMenu("Navigation/NavMeshLink", 33)]
    [HelpURL("https://github.com/Unity-Technologies/NavMeshComponents#documentation-draft")]
    public class NavMeshLink : MonoBehaviour
    {
primal needle
#

Hello. Anyone have experience with build Unity app for WebGL? I build my app and add it to my Asp.Net application. when it runs, I get an error that repeats: ```
Build.loader.js:1 exception thrown: RuntimeError: memory access out of bounds,RuntimeError: memory access out of bounds
at https://localhost:7191/Build/Build/Build.wasm:wasm-function[2879]:0xb958a
at https://localhost:7191/Build/Build/Build.wasm:wasm-function[11920]:0x3739ca
at https://localhost:7191/Build/Build/Build.wasm:wasm-function[14690]:0x509197
at https://localhost:7191/Build/Build/Build.wasm:wasm-function[14680]:0x508bc8
at https://localhost:7191/Build/Build/Build.wasm:wasm-function[31482]:0x8dcf13
at https://localhost:7191/Build/Build/Build.wasm:wasm-function[24633]:0x6bcf12
at invoke_i (https://localhost:7191/Build/Build/Build.framework.js:3:328923)
at https://localhost:7191/Build/Build/Build.wasm:wasm-function[24650]:0x6c4338
at Module._main (https://localhost:7191/Build/Build/Build.framework.js:3:279311)
at callMain (https://localhost:7191/Build/Build/Build.framework.js:3:340108)
at doRun (https://localhost:7191/Build/Build/Build.framework.js:3:340668)
at run (https://localhost:7191/Build/Build/Build.framework.js:3:340840)
at runCaller (https://localhost:7191/Build/Build/Build.framework.js:3:339767)
at Object.removeRunDependency (https://localhost:7191/Build/Build/Build.framework.js:3:16285)
at https://localhost:7191/Build/Build/Build.framework.js:3:1948
at doCallback (https://localhost:7191/Build/Build/Build.framework.js:3:93134)
at done (https://localhost:7191/Build/Build/Build.framework.js:3:93288)
at transaction.oncomplete (https://localhost:7191/Build/Build/Build.framework.js:3:86393)

swift falcon
#

Is it just deemed acceptable enough and left as is?

smoky saddle
#

does anyone have experiance with using il2cppinspector scaffolding to build mods for unity games?

ApplicationManager* appMgr = (ApplicationManager*)(GameObject_GetComponent(gameCtrl, GetType("ApplicationManager"), nullptr));

for some reason this line gives me the error Il2CppExceptionWrapper at memory location

somber nacelle
rigid island
swift falcon
#

Oh I didn't realize it hit 2.0 my bad

#

It was in 1.1.4 for ages if I recall, I thought it was abandoned back then

#

Think I confused it with that

rigid island
#

yeah it was they stripped , the one that comes with editor and they made it into this 1 package

#

the extras you meant

#

AINavigationExtras or w/e it was called

#

back in github days

rocky helm
#

Hello, so I have this function where, for some reason it says that the index was outside the bounds of the array over here:

            Vector3[] newVertices = {
                vertices[triangles[triangleStart]],
                vertices[triangles[triangleStart+1]],
                vertices[triangles[triangleStart+2]]
            };

Here is the full function in case you need it: ```cs
private GameObject[] GetFracturePieces(){
Mesh mesh = shatterMapPrefab.GetComponent<MeshFilter>().sharedMesh;
Vector3[] vertices = mesh.vertices;
int[] triangles = mesh.triangles;
GameObject[] fracturePieces = new GameObject[triangles.Length/3];

    for(int i = 0; i < triangles.Length/3; i++){
        int triangleStart = i+i*3;
        GameObject fracture = new GameObject();
        MeshFilter meshFilter = fracture.AddComponent(typeof(MeshFilter)) as MeshFilter;

        Mesh newMesh = new Mesh();
        Vector3[] newVertices = {
            vertices[triangles[triangleStart]],
            vertices[triangles[triangleStart+1]],
            vertices[triangles[triangleStart+2]]
        };
        int[] newTriangle = {0, 1, 2};
        newMesh.vertices = newVertices;
        newMesh.triangles = newTriangle;
        meshFilter.sharedMesh = newMesh;
        
        int firstEmpty = Array.IndexOf(fracturePieces, null);
        fracturePieces[firstEmpty] = fracture;
    }
    return fracturePieces;
}
Now, this is most likely due to me being a dumbass, so I'd guess it is something simple that I just forgot :p
pure cliff
rocky helm
pure cliff
rocky helm
knotty sun
#

man, it's pretty obvious that the value of triangleStart is not what you think it should be

pure cliff
pure cliff
knotty sun
#

indeed

rocky helm
pure cliff
#

Im shocked we dont have a !command for "use the debugger" in some capacity, cuz way to often the problems posted here are instantly solved with a single breakpoint

rocky helm
#

it just confused me because it said the error was on this line Vector3[] newVertices = { not the entire thing

pure cliff
knotty sun
#

people have problems using Debug.Log, using the actual debugger is like asking for nirvana

knotty sun
#

I know, you know, they dont want to learn, too much effort

pure cliff
#

the frequency I see people using debug logging when the button is like, right there lol, drives me up the wall @_@;

knotty sun
#

'I just want to make my game, wdym I have to learn shit first'?

rocky helm
knotty sun
rocky helm
olive karma
#

I have no idea what I coded wrong but for some reason my characters like always moving, btw its 3D, and when I walk of the edge the character like snapes to the edge and changes direction

soft shard
olive karma
#

oh I am currently investigating what script is doing it and I will paste the code

#

sorry

narrow blade
#

i am making a gun for my game does anyone know where i went wrong with this code

olive karma
#

and this is the CharacterJump code:

narrow blade
#

this is the full code

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Gun : MonoBehaviour
{
    private float Damage = 10;

    void Update()
    {
        if(Input.GetMouseButtonDown(0)) {
            Shoot();
        }
    }

    private void Shoot() {
        RaycastHit hit;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

        if (Physics.Raycast(ray, out hit)) {
            Debug.Log(hit.collider.name);

            private GameObject ShotObject = hit.collider.gameObject;
            
            if(ShotObject.GetComponent<Health>() != null) {
                ShotObject.GetComponent<Health>().myHealth -= Damage;
            }

            // if (hit.collider != null) {
            //         hit.collider.enabled = false;
            // }
        }
    }
}
#

also whats not working is the code

narrow blade
#

im getting errors

#

14

rocky helm
#

what are they?

narrow blade
#

line 21-32 i think

robust dome
#

"i think"

soft shard
#

Usually the first error cascades into the others, likely resolving the first may also resolve many, or all of the other 13 errors, though whats the first error say word for word?

rocky helm
fervent furnace
#

you dont need access modifier when declare local variable

narrow blade
#

1: Assets\Scripts\Gun.cs(21,42): error CS1513: } expected
2: Assets\Scripts\Gun.cs(23,13): error CS1519: Invalid token 'if' in class, record, struct, or interface member declaration
3: Assets\Scripts\Gun.cs(23,47): error CS8124: Tuple must contain at least two elements.

fervent furnace
#

the "private" GameObject

simple egret
#

private GameObject ShotObject = hit.collider.gameObject; - private is incorrect here

#

Only class variables can have access modifiers (private, public, etc.)

narrow blade
#

removed private

fervent furnace
#

and your vs code doesnt get configured correctly....

rocky helm
narrow blade
#

not yet i will add one to a test object sry

rocky helm
#

well then thats why it errors

narrow blade
#

yeah i did everything

rigid island
olive karma
#

for some reason when Im not even moving my character moves a littlebit and the character like snaps to the edge, ive figured out that its because of my weird hierarchy (character and the camera being children of the player gameobject) did I set something wrong?

rigid island
#

nvm discord stupid picture placement

olive karma
#

its in the players inspector

olive karma
rigid island
#

im still not used to it

olive karma
#

true

rigid island
#

for rotation

#

X + Z

olive karma
#

oh ty that worked

#

but I still have the other bug

#

but it solved the main issue

#

the other bug is just when I slip of the edge it totally changes the rotation of the camera for some reason

#

oh I found the issue :D

#

I just had to froze Y too

olive karma
olive karma
#

!code

tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

olive karma
#

sorry to boughter you guys but how do I make this code (https://gdl.space/ogohohoyeq.cs) make the jump not infinite but just make it 1 jump until I touch the ground again

misty blade
#

Hello! I'm having a weird issue with a class. Every time I reset my scene the List<Transform> named cameraBoundingPoints is lost (it has no elements). It appears to be reseted to default state being just new() List but from my understating it should remember it's state before entering playmode. So if a set lets say 3 elements in that list upon restarting the scene it should keep those three elements. It is also a private variable so no other classes have access to it. Does anybody know what I'm doing wrong here? I used lists a lot in my project and never saw that happen before

using UnityEngine;

public class LevelDataHolder : MonoBehaviour
{
    [SerializeField] private LevelData level;
    [SerializeField] private List<Transform> cameraBoundingPoints = new();

    public LevelData Level { get { return level; } }
    public List<Transform> CameraBoundingPoints { get { return cameraBoundingPoints; } }
}```
rigid island
#

then your new() is running again

#

you can use DDOL and keep the object from unloading

misty blade
#

do you know why doesn't it happen on other classes? I have almost identical list here for example and it keeps all it's data on every scene reload:

private List<RagdollPart> _radollParts = new List<RagdollPart>() { };```
#

could it be because it is a attached to a prefab?

somber nacelle
#

are you adding elements to the list at runtime and expecting them to persist across scene changes? or are they added at edit time?

misty blade
#

this list is not modified at all and it is not meant to be in runtime

#

only in editor

somber nacelle
#

then it should be loading the serialized values. what is the actual error you are getting?

misty blade
#

i'm not getting any errors in the console if thats what you mean

rigid island
misty blade
#

when I reload a scene, yes

somber nacelle
misty blade
#

right

somber nacelle
#

are you looking at the right object

misty blade
#

yes, I am certain about that

somber nacelle
#

you're looking at the one in the scene and not the prefab, yes?

misty blade
#

only one object is meant to have this class attached

#

and it is not a prefab

rigid island
#

how does the object stay there though if you switch scenes

#

inspector for it I mean

somber nacelle
misty blade
#

I asked about a different case there. I used lists quite a lot and they keep their data upon scene changing, but I thought it may be due to the fact that they are prefabs

#

the object I'm talking about is not

misty blade
somber nacelle
#

could you record this behavior?

rigid island
misty blade
coarse jackal
#

I am running into Unityframework issue. After I build to Xcode I am receiving the following errors:
.
I am believe these files are untracked by unity. therefore after the build they are getting lost somehow.
.
Any insight is greatly appreciated else I will keep on digging.

rigid island
coarse jackal
rigid island
static pier
#

Guys, i am trying to create an preview of the trajectory that an object will follow, before the game runs, so i can place objects more easily into orbit, the problem is i didn't find anything or any tutorial/forum post that really helped me.

#

oh btw am i in the right channel?

somber nacelle
#

do you have some equation that represents the path it will take? if so, you can use a line renderer and just sample different points in that trajectory equation to draw the line

misty blade
misty blade
somber nacelle
somber nacelle
# misty blade

that is certainly odd. have you tried saving the scene before entering play mode to see if that might fix it? i would assume that it shouldn't make a difference but since the scene is unsaved it's possible that could be the cause

#

if saving the scene doesn't fix it, try restarting the editor because this is definitely not how it should work. unless you have some other code that is causing a new object to be spawned

lean sail
# misty blade

looks like its losing the references cause all the children arent in the scene anymore

static pier
misty blade
somber nacelle
#

probably because the scene wasn't saved. so when you completely reloaded the scene, it loaded the version that was saved

rigid island
#

most logical way is usually the way lol

#

unsaved changes = list gets messed up on reload scene

#

unity keeps all that inside a yaml file

misty blade
#

alright, thanks everybody for helping out ;))

#

lesson learned

somber nacelle
static pier
somber nacelle
#

how are you actually applying this? because that equation is literally not a trajectory. it is just the calculation of the force of gravity. it has no direction which is, you know, the point of calculating a trajectory

static pier
#

i mean, with timestep you could technically preview the movement, every timestep

somber nacelle
#

well then congratulations, you have the equation you need. just change plug different time steps in to get different points for the line renderer

static pier
#

is there any extra equation i need to calculate the trajectory though

somber nacelle
#

what, was calculating just the force of gravity not enough for you? i thought you said you could preview the movement just from that ๐Ÿ˜‰

static pier
#

well i guess so, i just don't know how to work with trail renderer though

light rock
#

there is no "equation for a trajectory" a trajectory is a path. you need to simulate the physics in order to determine where the object will go over time. you can use Physics.Simulate to do this without actually waiting for it to simulate normally

#

if you want to preview the trajectory, you would want to simulate it for a given amount of time, recording its position regularly. then use a line renderer (not a trail renderer), then plug in those positions into the line renderer

somber nacelle
#
  1. there absolutely are formulas to calculate the trajectory of an object
  2. what if they aren't using unity's physics? they haven't actually said how they are moving the object despite my earlier question asking them
tawdry jasper
#

I'm finding conflicting info on how to ensure scriptable object changes are saved. If you just use a default inspector changes either are saved automatically when interacted with or when you hit ctrl+s, but what if I have a singleton scriptable object modified from other inspectors, How do I save my scriptable object instance to ensure the changes are serialized?

proper olive
#

If theyre not using Unity physics it needs some mathematics and physics knowledge
However if theyre using a rigidbody i found this example which might prove useful

https://github.com/llamacademy/projectile-trajectory/blob/main/Assets/Scripts/GrenadeThrower.cs

GitHub

Learn how to use a Line Renderer and a basic kinematic equation to show the trajectory of any projectile! We're using a grenade in this case, but it can be applied to cannon balls, bullets ...

light rock
#

yeah. but trying to give someone asking programming questions advice in the form of "go solve an n-body problem in astrophysics" isnt very useful lol

static pier
#

i use this

proper olive
proper olive
light rock
#

that example only works with objects with parabolic trajecetories. if youre doing a space game with planets it wouldn't work

#

especially 3+ bodies, which is what they drew in their example

proper olive
#

Hmm

static pier
#

i am indeed doing an space game with planets, and i plan to adding atleast Earth-Moon-Sun system

knotty sun
proper olive
#

My brain stopped workin here because the last time i did advanced physics was for a high school course 6 years ago

static pier
#

i am learning onto it

knotty sun
#

that aint gonna work, this is , literally, rocket science, you will need to understand it

static pier
#

well in that case i know enough of it to do this i think

light rock
#

not if u do it the way i suggested and just use Phsyics.simulate to let unity do it for you

proper olive
#

First this

knotty sun
light rock
#

?

#

the above function simulates the whole scene, which can have an arbitrary number of bodies

knotty sun
#

which will apply the same physics parameters to all of the bodies which, in a multi body physics scenario is not the case

light rock
#

well

#

you would turn off the auto simulation, then apply all the forces you want, then call simulate

light rock
#

i believe this value

#

by default it's FixedUpdate. but you want it to be Script when you're doing your preivew thing

static pier
#

so i use script to calculate the trajectory, and fixedupdate for the gravity calc?

light rock
#

yeah that's what i would do

cursive wing
#

I trying use fileStream to save multiple objects variables but i have no idea how to do that correctly

#

farthest I got was save a single object's variables

leaden ice
cursive wing
#

i use it to write save files

leaden ice
#

there's like 20 other steps involved in a save system

#

that are much more relevant to discuss

#

most importantly being:

  • what data are you trying to save
  • how are you serializing it?
shell scarab
#

I'm trying to set the position of a rect transform. This is my code, and this is what it's being set to:

RectTransform t = GetComponent<RectTransform>();

t.anchorMin = new Vector2(0.5f, 0.5f);
t.anchorMax = new Vector2(0.5f, 0.5f);
t.position = new Vector2(22, -15);
t.localScale = Vector3.one;
shell scarab
#

what many things?

cursive wing
leaden ice
#
  1. the position shown in inspector is relative to its parent
  2. the way that interacts with world space psotioon depends on which canvas render mode it's in
  3. Those numbers depend heavily on the anchor preset
#

you'll want to look at rt.sizeDelta and rt.anchoredPosition

shell scarab
#

sizeDelta sounds like it's for stretch mode

#

actually it just seems like one thing was wrong, not many things. I saw a property I didn't see before and that fixes it. Thanks anyways.

static pier
light rock
#

what are u struggling with

cursive wing
leaden ice
#

it's insecure

rare sandal
#

Bro my mums getting annoyed im staying up to 2am to code lmao

vagrant blade
#

Something I'm sure we all needed to know

cursive wing
leaden ice
#

literally anything else

#

most people go with Json serializers

#

for example Unity's JsonUtility

cursive wing
#

is it possible to JsonUtility achieve my main goal?

leaden ice
#

whats your goal

#

a save system?

#

Yes

cursive wing
#

a save system that let me save more than a single object

leaden ice
#

YOu're thinking about it the wrong way if you're asking that

cursive wing
#

I dont know much about save file creator systems

leaden ice
#

The general appraoch is you make an object called like SaveData

#

and wrap all of your data you want to save in it

#

then you serialize that and save it to a file

earnest gazelle
#

Have you used observable collections or implement it to show a list of some stuff with the ability of adding, removing element

#

. Net also has a collection observable collections to raise events when changes

simple ridge
#

Hi everyone, I'm unsure on if this is the correct chat to ask this in so please let me know if I should ask this in a different one as I realise this is more to do with general unity then code help. But I was wondering if I could get some help on an issue to do with script re-compilation times. The company I am working for has been working on a project for a while and recently script recompelation times have gotten extreme. To the point where making a single change in Rider will cause a 1:30 recompilation, then have the editor hang for a moment then pressing play also takes about another 1:30.

This seems to be happening to everyone on the team, though I am apparently the only one who is getting fed up with it, so is there a way I could potentially fix this? Are there any ways I can avoid re-compelations happening on minor code changes to code until play mode (unless its editor only code as that I will obviously need to happen when going back to the editor). And is there anything we can do to improve the time it takes to recompile anyway?

quartz folio
muted cave
#

Hey people! I've been having errors (8) in a script called "XRPokeFollowAffordance.cs". The script is included in the XR Interaction Toolkit.

These are the following errors:

#

Assets\Samples\XR Interaction Toolkit\2.3.0\Starter Assets\Scripts\XRPokeFollowAffordance.cs(2,26): error CS0234: The type or namespace name 'Bindings' does not exist in the namespace 'Unity.XR.CoreUtils' (are you missing an assembly reference?)

#

Assets\Samples\XR Interaction Toolkit\2.3.0\Starter Assets\Scripts\XRPokeFollowAffordance.cs(3,42): error CS0234: The type or namespace name 'AffordanceSystem' does not exist in the namespace 'UnityEngine.XR.Interaction.Toolkit' (are you missing an assembly reference?)

#

Assets\Samples\XR Interaction Toolkit\2.3.0\Starter Assets\Scripts\XRPokeFollowAffordance.cs(4,42): error CS0234: The type or namespace name 'Filtering' does not exist in the namespace 'UnityEngine.XR.Interaction.Toolkit' (are you missing an assembly reference?)

#

Assets\Samples\XR Interaction Toolkit\2.3.0\Starter Assets\Scripts\XRPokeFollowAffordance.cs(5,52): error CS0234: The type or namespace name 'Tweenables' does not exist in the namespace 'UnityEngine.XR.Interaction.Toolkit.Utilities' (are you missing an assembly reference?)

#

Assets\Samples\XR Interaction Toolkit\2.3.0\Starter Assets\Scripts\XRPokeFollowAffordance.cs(161,37): error CS0246: The type or namespace name 'PokeStateData' could not be found (are you missing a using directive or an assembly reference?)

#

Assets\Samples\XR Interaction Toolkit\2.3.0\Starter Assets\Scripts\XRPokeFollowAffordance.cs(100,9): error CS0246: The type or namespace name 'IPokeStateDataProvider' could not be found (are you missing a using directive or an assembly reference?)

#

Assets\Samples\XR Interaction Toolkit\2.3.0\Starter Assets\Scripts\XRPokeFollowAffordance.cs(102,18): error CS0246: The type or namespace name 'Vector3TweenableVariable' could not be found (are you missing a using directive or an assembly reference?)

#

Assets\Samples\XR Interaction Toolkit\2.3.0\Starter Assets\Scripts\XRPokeFollowAffordance.cs(103,18): error CS0246: The type or namespace name 'BindingsGroup' could not be found (are you missing a using directive or an assembly reference?)

#

This is it, but please help.

#

(DM ME IF YOU KNOW HOW TO FIX)

muted cave
#

-MonkePro2000

lean sail
# muted cave (DM ME IF YOU KNOW HOW TO FIX)

most of these look like you just didnt import something from the package manager. These errors are literally just tells you that something doesnt exist, when your code is trying to use it

muted cave
#

I know that, but what package do I have to import?

quartz folio
#

Googling one of those types you can find it's in the XR Interaction Toolkit

#

so presumably that's not installed

muted cave
#

It is

#

the toolkit is installed

quartz folio
#

Show it in the package manager

lean sail
muted cave
muted cave
quartz folio
#

2.0.4 seems quite low a version

muted cave
#

that's what I have, how do i update it?

#

not the unity version, but just the toolbox version

#

that's just the version of unity im using.

quartz folio
#

Did you install the starter assets via that button, or did you get them elsewhere?

lean sail
quartz folio
#

Odd. It says 2.3.0 in the samples directory

muted cave
#

I just had to re-import the assets. No more errors. Thanks for helping ig.

cursive wing
unreal oak
#

Hey, guys! I've just set up Git to version control my Unity project, and everything works amazingly so far. However, I can no longer see error lines in my code. Do any of you know how to fix this? I've tried a handful of things, but to no avail.

tawny elkBOT
#
๐Ÿ’ก IDE Configuration

If your IDE is not autocompleting code
or underlining errors, please configure it:

โ€ข Visual Studio (Installed via Unity Hub)
โ€ข Visual Studio (Installed manually)

โ€ข VS Code*
โ€ข JetBrains Rider
โ€ข Other/None

*VS Code's debugger plugin is unsupported.
We recommend using VS or Rider instead.

leaden ice
#

git won't have any bearing on it

#

it's about configuring your IDE

unreal oak
wide dock
#
// Upper-left corner of the sprite, middle of the screen (probably)
Vector2 position = Camera.main.WorldToScreenPoint(Vector2.zero); 

Vector2 size = new Vector2(texture2D.width, texture2D.height);

// Adjusting to the correct position
position = new Vector2(position.x - size.x / 2, position.y + size.y / 2); 

Rect textureRect = new Rect(position, size);

Graphics.DrawTexture(textureRect, texture2D);

Yo, I'm struggling a little bit to draw a texture on my screen, tried a couple of things but nothing seems to work. Could anyone tell me what I might be doing wrong?

swift falcon
#

hii, I'm using RigidBody2d (rb), and when I do rb.velocity = new Vector3(Speed* Time.deltaTime ,0,0); the character goes very slow, no matter how much the variable speed increases, it doesn't go faster, am I using time.deltatime correctly?

leaden ice
#

that doesn't make sense

swift falcon
#

why?

leaden ice
#

becasue velocity is veloicity?

#

If you're going 10m/s you're going 10 m/s\

swift falcon
#

ohhhhh, you're right, thank you ๐Ÿ˜…

#

sorry for the trouble

#

Might be a stupid question but how can I get my class to compile inside of NavMeshPlus's NavMeshLink class:

namespace NavMeshPlus.Components
{
    [ExecuteInEditMode]
    [DefaultExecutionOrder(-101)]
    [AddComponentMenu("Navigation/Navigation Link", 33)]
    [HelpURL("https://github.com/Unity-Technologies/NavMeshPlus#documentation-draft")]
    public class NavMeshLink : MonoBehaviour
solemn wren
#

How does one make those arrow dropdowns on scripts like the advanced dropdown on the event system for example?

somber nacelle
#

do you mean the foldouts? if so you can use a custom inspector, or you can grab something like naughty attributes which includes a Foldout attribute

somber nacelle
swift falcon
#

ok right yea i just overrode the class thanks

static pier
#

and some that i find calculate more things than what i need

light rock
#

if you have knowledge of programming you should be able to implement what i described pretty easily yourself. but if not, then maybe you should try to get more coding practice under your belt until youre more capable of making a system like this

static pier
#

how much knownledge would i need

prime widget
#

is there a way to display a scriptable objects inspector inside of a custom editor window?

soft shard
light rock
#

nothing wrong with using tutorials. but eventually you will want to create things that nobody has made a tutorial on (like right now). so thats why you gotta practice, research for yourself, participate in game jams, etc

prime widget
compact solstice
wheat loom
#

i have a question regarding bullet spread

#

the spread works, but now the bullet prefab comes out of the centre of the scene, not the gunTip transform

#

here is my code:

//calculate spread
Vector3 shootDirection = GunTip.transform.localPosition;
shootDirection.x += Random.Range(-spreadFactor, spreadFactor);
shootDirection.y += Random.Range(-spreadFactor, spreadFactor);
//fire the bullet
GameObject bullet = Instantiate(bulletPrefab, shootDirection, GunTip.rotation);
bullet.GetComponent<Rigidbody>().AddForce(GunTip.forward * bulletSpeed);
Destroy(bullet, 5f);

soft shard
soft shard
wheat loom
#

yes

marble swift
#

what could be the reason that when i am in air the force gets applied really fast pushing the character to the side immediately way to fast and characters stops again very fast but when doing jumping and using force on other objects it works perfectly normal

wheat loom
placid zephyr
#

[ outdated because i changed collision to other ]

lean sail
placid zephyr
#

would that make the normal movement less snappy

lean sail
#

It would make it so it is frictionless

placid zephyr
#

ok but how tf do i make it frictionless

#

i said i normally ask for help in beginner chat so who are you to assume my knowledge

#

istg why tf do i always sound so rude

lean sail
#

"Unity 2d how to make my object frictionless" will definitely find you some results

leaden ice
#

show code

#

also every GameObject has a layer

#

you also never really showed the inspector of the wall

#

you only showed with the wall selected + other objects at the same time

#

show full script !code

tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

leaden ice
#

I see it

#

OnTriggerXXX is a little fishy?

#

does that mean your colliders are triggers?

#

what other components are on the player?

lusty dune
#
if (view.IsMine)
        {
            RaycastHit info;
            Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition);
            if (Physics.Raycast(ray, out info, 1000, LayerMask.GetMask("Default")))
            {
                //This can be used to access the 2d array for both chesspieces and chessboard tiles
                Vector2Int hitPosition = LookupTileIndex(info.transform.gameObject);


                //Is it our turn
                if (chessPieces[hitPosition.x, hitPosition.y] != null)
                {
//rest of code
}}}

man, im getting NRE on chessPieces[hitPosition.x, hitPosition.y] and i can't figure out? which knowledge am i lacking?

lean sail
lusty dune
#

yes

#
    private ChessPiece[,] chessPieces;
lean sail
#

you have to do = new ChessPiece[some int, some int]; at one point

lusty dune
#
 private void SpawnPieces()
    {
        chessPieces = new ChessPiece[TILE_COUNT, TILE_COUNT];
//...
lean sail
#

try running through the debugger then and seeing whats null. Im inclined to say that you are accessing chessPieces before SpawnPieces, but with just snippets of code i cant firmly say anything

lusty dune
#

i think problem lies in connecting random room

#

everytime i open 2 builds they join different rooms

rigid island
lusty dune
lusty dune
#

this is the whole script.. i gonna work on the room thing tomorrow though

pure cliff
#

Aight, anyone have example code for a CallbackContext with input system to handle individuating "single press" from "hold"?

#

specifically: repeatedly triggering an effect while the button is held down?

gray mural
#

Does anyone know why I cannot access my method?
ASP.NET application: https://www.nombin.dev/ekpogqx5ig

// Unity client

using (UnityWebRequest api = UnityWebRequest.Get(apiUrl))
{
    yield return api.SendWebRequest();

    if (api.result != UnityWebRequest.Result.Success)
    {
        Debug.LogError("Error sending request: " + api.error);
    }
    else
    {
        Debug.Log("Response: " + api.downloadHandler.text);
    }
}
#

it throws me that api.error here

gray mural
pure cliff
#

also you should see a debug log on your asp.net project as well, it'll inform you if requests are being rejected

pure cliff
gray mural
#
https://databasemanager.azurewebsites.net/PlayersDatabase/DoSomething
pure cliff
#

oh wait, surprised I didnt see that sooner

gray mural
#

but you cannot open this site, just https://databasemanager.azurewebsites.net

pure cliff
#

all controllers in Asp.Net need to be <Something>Controller as their name

#

but also how come you arent just testing this locally?

gray mural
gray mural
#

Route?

pure cliff
#

the class name itself

#

for that endpoint you want it to be named PlayersDatabaseController

gray mural
#

I don't get it

pure cliff
#

(Asp.Net does magic automatic fetching of Controllers by specifically looking for classes named <Something>Controller)

#

public class PlayersDatabase : ControllerBase

gray mural
#

so .../PlayersDatabaseController/DoSomething ?

pure cliff
#

^^^ its missing Controller at the end, so it wont get picked up by the AddControllers in Startup.cs

pure cliff
#

when you do

[Route("[controller]")]

It maps it to everything except the Controller in the class

#

so

[Route("[controller]")]
public class PlayersDatabaseController : ControllerBase

Will map to ~/PlayersDatabase/

gray mural
#

yes? so that initial url should be correct ??

pure cliff
#

yes

#

you just have to fix your class name and it should be good

gray mural
#

oh.

#

it's about the class name?

#

is there any way I can do it without changing the class name?

pure cliff
#

just name your controllers correctly so they get registered properly

gray mural
#

I see

pure cliff
#

Over in Startup.cs you'll see a call to .AddControllers or whatever, or .AddMVC or something like that.

It "automagically" scrolls through looking for classes you have named <Something>Controller and will register them, if you dont name em right, they get missed

gray mural
#

anyway, it still throws me an error.

#

the same one

#
namespace DatabaseManager.Data
{
    using Microsoft.AspNetCore.Mvc;

    [ApiController]
    [Route("[controller]")]
    public class PlayersDatabaseController : ControllerBase
    {
        [HttpGet("DoSomething")]
        public IActionResult DoSomething()
        {
            return Ok("DoSomething method worked");
        }
    }
}
pure cliff
#

That looks correct now

gray mural
#
private const string apiUrl = "https://databasemanager.azurewebsites.net/PlayersDatabaseController/DoSomething";
pure cliff
#

bruh

gray mural
#

wait

#

do I have to write everything from small letter, no?

pure cliff
pure cliff
gray mural
#

but it still throws an error.

pure cliff
#

Also I will heavily recommend you just test locally to save a lot of future headache

pure cliff
gray mural
pure cliff
#

Test locally to start

#

Adding all the wild stuff for routing and DNS and shit on top of this is a lot, testing locally removes all those variables at least

gray mural
pure cliff
#

it sure will remove a lot of potential problem causing variables from the equation

pure cliff
#

just run the project and you should get a console window that shows you a localhost url its listening on

#

use that as your domain for now (same endpoint)

gray mural
#

does my local site work even when my application isn't opened?

pure cliff
#

which application?

gray mural
pure cliff
#

you have asked "is the server running when it isnt running" effectively :x

gray mural
#

actually I haven't, I can access my site even if my visual studio is closed.

pure cliff
#

I mean you can run it manually but like... just debug it with visual studio, you can even add it to your unity solution so you can debug both at the same time nicely

gray mural
#

I see, I will try to make if local first

pure cliff
#

I havent personally tried this yet but it should work as long as you dont regenerate the project (you'll have to just re-add the project again)

gray mural
pure cliff
#

You'll then wanna hit this, and add your Asp.Net application as part of your startup projects

pure cliff
pure cliff
#

Coolio

#

yeah you basically just hit "add existing project" and go click that .csproj file for your asp.net app

gray mural
#

I see, done

pure cliff
#

then you will wanna right click on the project, and hit that button "Configure Startup Projects"

#

And swap to Multiple startup Projects,

You'll wanna have Assembly-CSharp and DatabaseManager both set to Start and thats it, should be good to go

gray mural
#

I have them in the same solution now ?

#

but do I really need this?

pure cliff
#

Id strongly recommend it

gray mural
#

I think it shouldn't be done

pure cliff
#

why?

gray mural
#

unity is a client

pure cliff
#

Indeed

gray mural
#

every player has unity client project

#

and ASP.NET project manages postgres database

pure cliff
#

Yup

gray mural
#

so C# application is just one

#

1 instance of it.

#

are you sure they should be in the same solution?

#

I think I just don't understand something

pure cliff
#

What issue are you forseeing them being in same solution

pure cliff
gray mural
leaden solstice
#

I would have separate solution for server project

pure cliff
#

The other thing you very likely will want soon, is a .Common project that will hold your classes for your API endpoints

leaden solstice
#

Unity sln is Unity generated in their flavor.

pure cliff
gray mural
#

anyway, it doesn't make me able to access that method ? ๐Ÿค”

leaden solstice
#

You don't want to put that in a git, you don't want to modify your sln every machine / every time Unity regenerate.

pure cliff
#

I mean in a professional enviro I would have:

  1. Git repo for the unity project
  2. Second repo for the API
  3. Third repo for the "common" layer, that is a Nuget pkg reffed by both above but has Debug/Release switch flip in their respective .csproj for if its direct ref vs nuget ref
  4. a Parent repo with a submodule reffing the three above and a .sln file that brings em all together, and it would have my stuff like docker configs and whatnot, build pipeline yamls, all that jazz

Thats how I do it at my job when Im having to synch up with teams and whatnot

gray mural
#

too many repos

#

hate my typos

pure cliff
# gray mural too many repos

thats how it be, it can get even zanier if your frontend isnt unity, but is a web app with NPM packages as well

#

I mean if you have locally maintained unity packages, you'd wanna keep those in their own repos as well and submodule em in

gray mural
#

yes, it makes sense

#

I think I should do it later

#

if I fix access to method UnityChanThink

pure cliff
#

but yeah I dunno if unity is gonna fuck with that .sln file much

#

but I havent tried it myself, Id give it a shot, if it keeps over and over removing that project ref then forget about it

#

I presumed unity only messes with the .sln file if you click the regenerate button

gray mural
#

but should this site be accessible in the internet?

https://databasemanager.azurewebsites.net/PlayersDatabase/DoSomething
#

or no?

pure cliff
gray mural
#

yes, it doesn't work for me too

pure cliff
#

if you run it locally it should just be running on https://localhost:SomePort

gray mural
#

but you will still be able to access https://databasemanager.azurewebsites.net ?

pure cliff
#

when you run the server locally you are literally running it on your machine purely for testing and verification purposes

#

once you confirm that it works locally, then you can test it up on azure

gray mural
#

yes, it works locally

pure cliff
#

testing on azure first is a good way to go insane because how would you know if the issue is with your code, or your azure configuration, or your DNS resolution, or something else?

pure cliff
# gray mural yes, it works locally

aight, I dunno how you are pushing to azure but, if it works locally and the endpoint gets hit, then yeah next Id test if pushing to azure works

gray mural
#

but it works very strange

#

it opens me a localhost site once I click on StartDebugging

#

but when I close the site that it has opened, I cannot access it anymore

#

I think I have to find nice documentation for it

#

thank you for your help! ๐Ÿ™‚

pure cliff
#

if you wanna test your azure site, you gotta publish and push to azure

#

clicking that Start Debugging button is purely just for running and debugging locally

thin idol
#

im making an fps game

#

and it works but the sensitivity is too low

#

how do i make sensitivity higher

#

yes i know im lazy

prime sinew
thin idol
#

i litterrally have no darn tootin idea how to use c script

#

this is my first time using unity

rocky helm
#

Hey so, how could I get all the vertices on the same plane of a mesh while assuming that both sides are symmetrical? For example, lets say we have a cube as seen on the picture. I would need to somehow get the top or bottom vertices and save them in a script as the red ones, but this should work on any object that has symmetrical top and bottom like a cylinder as well.

thin idol
#

so i have no idea where is the mouse logic

simple egret
#

Shouldn't be copying some random code then, learn and roll your own

prime sinew
simple egret
#

:learn

tawny elkBOT
#

๐Ÿง‘โ€๐Ÿซ Unity Learn can offer you over 750 hours of free live and on-demand learning content for all levels of experience! Make sure to check it out at https://learn.unity.com/

thin idol
# prime sinew !learn

the tutorials said to use pastebin if the tutorials work in blender they must work in unity

prime sinew
#

No point we give you instructions if you won't understand what we're saying

rocky helm
#

Like I would need the vertices of the object that you would see when you look at its front in a 2d view

leaden solstice
rocky helm
rocky helm
#

But my problem is how

#

Like I need to get the vertices that are on the same plane as the transform.forward facing face on the mesh

#

oh shit

#

I can use triangle.normal

thin idol
#

i think i need to change the red numbers

mellow sigil
#

You don't think the variable named "lookSpeed" would be more likely?

thin idol
gray mural
wide fiber
#

why when i put the same input it has an error? my "Get" didnt show up on the intellisence.

void OnMove(InputAction value) => moveInput = value.Get<Vector2>();```
#

the one on the attachment is ok. this is from a youtube tutorial

#

but the one i put on it has error on my "get"

#

why? ๐Ÿ˜ฆ

simple egret
#

The parameter type is different

#

InputAction / InputValue

wide fiber
#

hahaha . sorry for that. thank you so much btw

civic vigil
#

Hello, does anyone have any advice or can point me in the right direction on how to implement acceleration and deceleration in my character controller? I'm using the charactercontroller component.

tawdry jasper
#

Anyone setup the newtonsoft json package? The docs say that by simply installing it will (https://github.com/jilleJr/Newtonsoft.Json-for-Unity.Converters#sample-with-this-package) but even though I have added this package to my project, when I try their example and simply serializing a Vector3 value, I get the problem they're mentioning should only happen without it (JsonSerializationException: Self referencing loop detected for property 'normalized' with type 'UnityEngine.Vector3'. ) I think I only installed the newtonsoft.json package, NOT the json-for-unity converters one...

somber tapir
simple egret
#

Or make a custom JsonConverter<Vector3>, but yeah that's exactly what the extension is doing herฤ“

tawdry jasper
#

trying to find that in the registry I found that there's actually a builtin JsonUtility.ToJson / FromJson<T> that actually do what I need (it serializes Vector3 and List<string> which is all I need for my gamestate)

lime niche
#

Is it bad practice to recreate a game's player movement without using its source code and using the math that they are using?

lime niche
prime sinew
#

Is it to achieve the same result your way, or to make an exact copy

#

If it's the latter, you might as well just copy paste the code since you have access to it

lime niche
#

I'm not really recreating it, I'm recreating the base of it then building up with my own mechanics.

#

I just though if I were to recreate it on my own, adding my own mechanics would be much faster.

prime sinew
#

At that point I don't think you should focus on how similar it is to the source code

lime niche
#

Ah.

rocky helm
#

So, about making a custom mesh at runtime, does the game object pivot point go to the center of the mesh (probably not)? If not, how could I move the vertices to have the pivot point be in the center of the mesh while keeping the same shape?

proper olive
#

ive been meaning to ask
Is it possible to use both cinemachine and the normal unity camera system in a single scene? I only want cinemachine for cutscenes as im actually using a custom fps camera and controller and moving to cinemachine for fps camera is meh

#

Like if i disable the cinemachinebrain and all virtual cameras would a normal camera work fine? I think in my tests it did work fine but i wanna know if anyone found any problems down the line with this

tribal ginkgo
#

Cinemachine is just another version of a camera as long as you disable them when not in use it wont bother the regular cameras. (I havent tried it personally but i dont see any way it could affect each other)

proper olive
sudden hinge
rocky helm
# sudden hinge The mesh is in local space, so it depends how you set up the mesh. If you start ...

I know that it is in local space, but the problem is that my mesh's starts off at like 2,0,0 (this is the furthest it can be on the x axis*) from the pivot point and so the vertices are around position, but I want the pivot to be in that position too, so the best thing I can come up with right now is to move all the vertices by x,y,z towards the pivot and then move the whole gameobject by -x,-y,-z to give the effect of moving the pivot, but I just dont know how to do it while keeping the shape the vertices make the same

#

The only information I have to do this with is the pivot point and the vertices positions.

sudden hinge
#

If you change the vertex pos of all vertices the shape will stay the same

rocky helm
#

Well, I guess I could probably get the bounds position, move all the verts by the -amount of how far the bounds are from the pivot and save that, then move the pivot by the same amount back

final gazelle
#

Hey, so I made a script that brings the player to the next level if he touches the object this script is attached to. But for some reason it only works in Level 1 and in the next Levels it just doesn't work anymore, even though i copied the exact same object. Does anyone know a solution to this problem? here's the script:

simple egret
#

!vs

tawny elkBOT
#
Visual Studio guide

If your IDE is not underlining errors in red or autocompleting code,
please configure it using the link below:

โ€ข Visual Studio (Installed via Unity Hub)
โ€ข Visual Studio (Installed manually)

simple egret
#

See the guide above

final gazelle
#

still doesn't work

#

I don't have that problem with other scripts I made

simple egret
#

Close VS, move the script from one folder to another and back in Unity, and open it again

#

This should trigger a compilation and solve it

final gazelle
#

okay thanks

pure cliff
#

Quick sanity check cuz I havent had my coffee yet:
This is the right way I go about "toggling" a flag for a flagged enum right?

public void OnMenu(InputAction.CallbackContext context)
{
    GameState.SceneState ^= SceneState.Menu;
}
simple egret
#

Yup looks good to me

fringe ridge
#

how the hell do i rotate canvas with screen space overlay? I'm sorry but it's straight up dumb that screen space overlay canvas matches with game mode, but simulator mode just gives the canvas in the wrong direction

pure cliff
# fringe ridge

for some reason the simulator isnt rotating the screen itself, thats odd

#

you shouldnt need to rotate at all, your phone itself handles the rotation on its own

fringe ridge
#

yeah, but It's really hard to redesign the whole UI for portait mode, when everything in scene will be flipped 90 degrees

#

after an hour of trying to fix it, i just pressed play and it automatically went into portrait mode

#

sometimes i seriously hate game dev

mint cosmos
#

Hello, why am i getting this error message in my own voice chat system?
Length of recording must be less than one hour (was: 220500 seconds)
when I just pressed the PTT key for half a second?

simple egret
#

Nobody sane enough will download an archive file from a complete stranger on the internet

#

Please post the !code as a code block or to a paste website

tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

mint cosmos
#

Will paste 3 files then

simple egret
rigid island
simple egret
#

Not everybody can see these embeds

mint cosmos
olive karma
#

I wanna add my audio files in the clips section and I need to drag and drop them from the project window but when I select the files it changes the window in inspector to the audio file instead of the player. can someone please help?

simple egret
#

Lock the Inspector on your object by clicking the "Inspector" tab at the top > Lock

#

It won't go away until you unlock it

olive karma
#

ty my friend

rigid island
# olive karma ty my friend

another neat trick to keep in mind if you wanna do it on multiple script or just never bother locking the inspector you can pop out the script if you right click it and click Properties

olive karma
#

oh thats interesting

#

ty for that too

#

also does anybody know why its not actually playing any sound when Im in the game

#

I will paste my entire code here

rigid island
#

are you sure the window is not muted ?

olive karma
#

!code

tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

rigid island
#

tryina find an image on google lol

olive karma
#

oooooh

#

it is

#

xD

#

ty

rigid island
#

๐Ÿซก

olive karma
#

I remember I turned it off because I was testing a unity asset and it was really loud

#

never turned it back on

gaunt blade
#

Does anyone know why Mathf.PerlinNoise() is returning "NaN"?

#

Bit confused how that's even possible

rigid island
gaunt blade
#

When it's suppose to be a float value

olive karma
#

NaN is "Not a Number" thats all I know

gaunt blade
#

Well yeah, but I'm confused how it's returning "Not a Number" when the function is suppose to return a number

#

Like how is that even possible and why is it happening

olive karma
#

NaN is technically like a non existent number

#

its like an undefined number

gaunt blade
#

I don't get how. I'm not dividing anything by 0

#

I don't think I am at least

olive karma
#

well its like "Math error"

#

for example 0/0 is math error

#

aka NaN

#

or for example

#

square root of negative numbers is a Math error

#

aka NaN

#

thats all I know

#

sorry for not really helping but I tried to at least explain what NaN is

gaunt blade
#

So is the PerlinNoise function broken or something I'm confused why there'd be an invalid math operation being returned by a built-in function

somber nacelle
gaunt blade
#

Okay

#

Oh I figured it out. I rotated the polygons to be along the x/z axis but forgot to modify some functions to account for that

indigo arrow
#

Does anyone have an idea on how I would go about creating an upgrades/items system like Enter the Gungeon and Binding of Isaac have? I've been looking everywhere and can't find a useful answer

#

I've tried abstract classes but it isn't seemingly what I'm trying to go for

#

e.g one upgrade may increase your health by 2, whilst another could summon a fireball every 3rd shot etc.

#

I need to be able to have them in a list and call their functions, whilst having different code inside?

gaunt blade
#

That'd deped entirely on how to choose to implement it. There isn't some sort of way to implement that system in a few lines of code

indigo arrow
#

I'm aware, I'm just tring to find some sort of idea on how to make it, not code itself.

full rune
#

can anyone help me with adding walking animations to my character

indigo arrow
proper olive
olive karma
#

I somehow messed up can somebody tell me how do I get back to the main scene from the UI thing cuz I was making health UI and now Im stuck in it

proper olive
#

If you want abilities just add bools to activate or deactivate them from

#

Ive never played the aforementioned games so sadlt idk how they work but if like with each lvl you want to gives options to increase health or add ability damage this works

indigo arrow
#

i thought of that but it didn't seem like a very neat way to implement it.

oblique narwhal
proper olive
#

Its simple
You can expand and fix it later on

indigo arrow
#

games like these have lots of items with lots of different abilities which means lots of bools and other such things

proper olive
#

Create a prototype of your system and make it more clean as you progress

proper olive
#

Almost every project ive done had the ugliest things imaginable but i cleaned them up as i went along

indigo arrow
#

similar to a scriptable object but not exactly?

oblique narwhal
#

In fact you'll notice monobehavior is not mentioned in the diagram

indigo arrow
#

ah

oblique narwhal
#

IF you change your mind and decide you do want it to have Monobehavior in the mix then have the BaseUpgrade inherit from Monobehavior.

olive karma
#

can someone please help me get back from this to my 3D game?

proper olive
#

It throws funky errors

oblique narwhal
soft shard
olive karma
soft shard
oblique narwhal
# proper olive You cant attach non mono behvaior scripts to GameObjects afaik

Correct - but he just said he didnt want it to be monobehavior.

You CAN however compose a monobehavior class with objects inside of it that are not derived from monobehavior such as:

`
public class MyGreatUpgrade: MonoBehavior
{

private NukeUpgrade nukeUpgrade;

private void Start()

{
nukeUpgarde = new Uprgrade();
}

}
`

olive karma
oblique narwhal
indigo arrow
soft shard
night storm
olive karma
night storm
oblique narwhal
# olive karma

Also of note ... you are in "2D" mode which sort of restricts your ability to navigate the scene in 3D. Theres a tiny extra set of button on the "Scene" strip one of which is "2D" maybe thats confusing you?

olive karma
#

this happens when I click 2D

soft shard
#

You can also select any object from your hierarchy and hit "F" while your mouse is over tthe Scene view, and the camera should focus on that object

night storm
olive karma
#

nope thats not how it works

#

theres not the world

indigo arrow
olive karma
oblique narwhal
olive karma
#

but I somehoe need to go back to the real 3D world

night storm
indigo arrow
spring creek
oblique narwhal
#

In this example because DisplayUpgrades is meant to display them to the player, its likely that class extends Monobehavior

peak thicket
#

Hey all, I'm running into an interaction I'm unfamiliar with.
I have two classes: Unit and SubmittedCommand. The Unit class has an array SubmittedCommand[] submittedCommands, which I instantiate as submittedCommands = new SubmittedCommand[5] inside of Unit.Awake(). I ran a Debug.Log right after the instantiation, and submittedCommands is now a list of 5 null entries. This is good, and what I want/expect.
Now heres whats confusing me; if I mark the SubmittedCommand class as [System.Serializable], after the Unit.Awake() call, the submittedCommands array now contains 5 created SubmittedCommand instances (all with null fields).
How come [System.Serializable] is populating this list?

#

I can provide code/screenshots/etc if needed

indigo arrow
oblique narwhal
#

if you look at the diagram, you'll see I included that as an Image already

indigo arrow
#

ooooh

#

alright thanks man

#

will implement it now!

jaunty sleet
#

Does anyone know how to detect if a touch is over the UI?

sick flint
#

Can someone help me, If I click middle mouse or right click it comes off of focus but if I click left click or escape it stays. Could it be something with a right click menu or something? nameMonsterUI.monsterNickname.onEndEdit.AddListener(val => { if(Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.KeypadEnter)) { Submit(); } else if (Input.GetMouseButton(0) || Input.GetMouseButton(1) || Input.GetMouseButton(2) || Input.GetKeyDown(KeyCode.Escape)) { nameMonsterUI.monsterNickname.Select(); nameMonsterUI.monsterNickname.ActivateInputField(); } });

#

I am using tmp_inputfield

jaunty sleet
sick flint
#

ah okay, should I just change the keybinds in there then?

#

I don't need mouse input for anything else

sick flint
jaunty sleet
#

Oh, I've never used a tmp input field so idk about that part. I just saw that you are using Input.GetKeyDown

simple egret
#

Not sure you can with that onEndEdit event, it's probably getting called after focus is lost. See if you can inherit from TMP_InputField and provide your own focus logic by oveeriding some methods (if you even can)

jaunty sleet
#

It's easier to use the new system, so switching will make your code simpler and then maybe you'll see why it isn't working

sick flint
carmine carbon
#

Is there a wayto not use system.reflections if I dont know which script I am gonna run method from? Like I have variable var component and want to run ethod from it?

simple egret
#

The sub-class will provide its custom implementation

carmine carbon
jaunty sleet
# sick flint I will have to research how to use that with what I am trying to do

You just make a InputAction field for your script, and serialize it so you can set it in the editor. Then go in the editor and set the key you want to trigger this input action. Unity makes this part very easy. Then go in your script and add a method you want to be called when the key is pressed. Add the OnEnable and OnDisable methods to your script. Add: inputActionName.performed += methodName(); and inputActionName.Enable(); to the on enable method, and vice versa for on disable. Now whenever the key is pressed, the method you made will be called

sick flint
simple egret
# carmine carbon May you give me example? I dont quiet understand. I was using this for now: Me...

Let's say you're making a damage system. But you also want to use that system to activate stuff (shoot buttons to activate them).
You can make an interface IDamageReceiver that has a Damage() method, like this

interface IDamageReceiver {
    void Damage();
}

And then have an enemy implement that

public class Enemy : MonoBehaviour, IDamageReceiver {
    public void Damage() { // you are forced by the compiler to implement this
      Die();
    }
}

And the button

public class Button : MonoBehaviour, IDamageReceiver {
    public void Damage() {
      Activate();
    }
}

Then on the gun, no matter what you hit, you try to get the interface instead of a concrete class, and use the method on it

ray.gameObject.GetComponent<IDamageReceiver>().Damage();

Then whatever you hit, be it an enemy or button, C# will take care of running the correct method.

#

And of course interface methods are like other methods, so they can accept arguments and return a value
They don't have to be void ...()

sick flint
jaunty sleet
sick flint
#

Ohโ€ฆ

jaunty sleet
#

lol

olive karma
#

!code

tawny elkBOT
#
Posting code

๐Ÿ“ƒ Large Code Blocks
Large code blocks should be posted as links to services like:
https://gdl.space/, https://paste.ofcode.org/, https://hatebin.com/
https://paste.myst.rs/, https://hastebin.com/

๐Ÿ“ƒ Inline Code
Surround code with three backquotes. Not quotation marks.
To get C# formatting the first line should only contain cs or csharp.
Add a comment with a line number if there is an error message.
```cs
// Your code here
```
Do not share screenshots of code unless requested.

jaunty sleet
#

They activate when the script is enabled and disabled, you want to use them when using the new input system as I showed you before to ensure a method is not called when the object it is on is disabled, which would case an error

sick flint
#
    {
        inputAction.performed += Submit();
        inputAction.performed.Enable();
    }

    void OnDisable()
    {
        inputAction.performed -= Submit();
        inputAction.performed.Disable();
    }

    public void Submit()
    {
        if(!inEvent)
        {
            StartCoroutine(nameMonsterUI.DeselectInput());
            StartCoroutine(ShowChoice());
            inEvent = true;
        }
    }```
#

I am getting errors for the inputAction.perform

jaunty sleet
#

What error are you getting?

#

I don't see any problem with that code so idk

#

oh you realize input action is just the name of an InputAction field right?

#

do you have an InputAction field named inputAction somewhere

sick flint
#

yeah thats serialized

#

[SerializeField] InputAction inputAction;

jaunty sleet
#

What is the error you get?

sick flint
#

Cannot implicitly convert type 'void' to 'System.Action<UnityEngine.InputSystem.InputAction.CallbackContext>'

jaunty sleet
#

oh my bad I forgot about part of this

#

You have to put InputAction.CallbackContext context as a parameter

#

in the method

somber nacelle
#

when subscribing to an event you subscribe the method group which means you don't include the ()

jaunty sleet
#

that too

sick flint
#
    {
        inputAction.performed += Submit;
        inputAction.performed.Enable();
    }

    void OnDisable(InputAction.CallbackContext context)
    {
        inputAction.performed -= Submit;
        inputAction.performed.Disable();
    }

    public void Submit()
    {
        if(!inEvent)
        {
            StartCoroutine(nameMonsterUI.DeselectInput());
            StartCoroutine(ShowChoice());
            inEvent = true;
        }
    }```
jaunty sleet
#

you put the parameter on submit

sick flint
#

nice

#

do I have to += enable and disable too

#

its saying it can only go on the += or -=

jaunty sleet
#

?

sick flint
#

inputAction.perform.Enable() is throwing an error

jaunty sleet
#

Oh your not supposed to put any parameters on enable and disable btw

sick flint
#

yeah I got rid of those

#

The event 'InputAction.performed' can only appear on the left hand side of += or -=

#

thats the error

jaunty sleet
#

idk

sick flint
#

I'm dumb

jaunty sleet
#

looks like its on the left to me

simple egret
#

Yup outside the class that declares the event, you can only use += or -=

sick flint
#

its just inputAction.enable and disable not performed

jaunty sleet
#

oh, I didn't notice you doing that lmao

sick flint
#

so this should work ``` void OnEnable()
{
inputAction.performed += Submit;
inputAction.Enable();
}

void OnDisable()
{
    inputAction.performed -= Submit;
    inputAction.Disable();
}

public void Submit(InputAction.CallbackContext context)
{
    if(!inEvent)
    {
        StartCoroutine(nameMonsterUI.DeselectInput());
        StartCoroutine(ShowChoice());
        inEvent = true;
    }
}```
jaunty sleet
#

yes

sick flint
#

without calling the OnEnable or OnDisable anywhere

jaunty sleet
#

Yeah, they get called automatically when the object is enabled and disabled