#πŸ’»β”ƒcode-beginner

1 messages Β· Page 23 of 1

ivory bobcat
#

If not, your action input may not be setup correctly

wanton hearth
#

This is what it looks like, I want E to be the action key, anything wrong here?

wintry quarry
#

it should be a keyboard key

#

or whatever that option is called

abstract finch
#
    {
        while (_camera.fieldOfView != targetFov)
        {
            _camera.fieldOfView = Mathf.Lerp(_camera.fieldOfView, targetFov, duration);
            yield return new WaitForSeconds(Time.deltaTime);
        }
    }

For some reason this coroutine is zooming in the field of view faster than it should I put it at 1 second but it goes to the target FOV within .1s

rich adder
#

not sure what this is even supposed to do
yield return new WaitForSeconds(Time.deltaTime);

wanton trench
#

Hey. for some reason my player character tends to walk towards the left randomly without me giving it any input. i already looked at the debug.log and it seems that sometimes it gets an random input which is like -0.00068 and so on. Here is the method which handles the running

void Run()
{
Vector2 playerVelocity = new Vector2(moveInput.x * runSpeed, rigid.velocity.y);
rigid.velocity = playerVelocity;

    bool playerIsMoving = Mathf.Abs(rigid.velocity.x) > Mathf.Epsilon;
    

    if(playerIsMoving)
    {
    myAnimator.SetBool("IsRunning", true);
    }
    else
    {
    myAnimator.SetBool("IsRunning", false);
    }
 
}
steep coral
#

Why do i get a error at Transform parent

languid spire
#

because you cannot declare a variable in the middle of that API call

steep coral
#

and what shall i do

gaunt ice
#

transform.parent?

steep coral
#

I want it to instantiate under a certain object

abstract finch
ivory bobcat
gaunt ice
#

i havent took a look at the api yet, you have to check it

ivory bobcat
abstract finch
rich adder
ivory bobcat
wanton trench
short hazel
wanton trench
#

i feel stupid right now

rich adder
abstract finch
abstract finch
steep coral
#

didnt get what i wanted

short hazel
#

Well at least it compiles now

languid spire
ivory bobcat
steep coral
#

idk man

#

making a board gaem is way difficult that platformer

languid spire
#

but which object is this?

steep coral
#

which meaning ?

short hazel
#

You want clickedTile.transform most likely (the tile you hit). Not the parent of the tile you hit

steep coral
#

its not doing it

#

it still shows up hierarchy under scene not where i want it

short hazel
#

Then it's the second Instantiate that runs, when it's not "the tiger's turn"

sacred zenith
#

Hello,
If I raycast the Terrain with the boxcast, will it return only the first point to touch terrain, or every point?
I am trying to implement a tool that affects the terrain in a certain area

short hazel
#

First point. A box cast is merely just a thicker raycast

sacred zenith
#

I see, do you have any suggestion to my problem? I tried defining a starting and ending corner and simply looping from one to the other, but it seems bad

#

specially since raycast coords and texture coords operate on separate spaces

short hazel
#

What you can do is a BoxCastAll

#

Returns an array of colliders

sacred zenith
#

Nice, will try

#

Thank you

sage spruce
#

Hello, I am instantiating a ground (basically a cube) with some enemies on it. After I kill the enemies in the first ground, rest of the instantiated grounds comes with allready dead enemies. I thought every prefab was suppose to be unique and not get effected by the previous alterations. Any idea what I am doing wrong ?

languid spire
#

probably re-instantaiting the ground gameobject rather than the ground prefab

sage spruce
#

I drag from the prefab folder not the game object in the scene

languid spire
#

I meant in your code

sage spruce
#

a little frustrating πŸ˜„

#

Instantiate(groundCube, RBspawnPoint.position, RBspawnPoint.rotation);

#

this is the code I use

languid spire
#

just that?

sage spruce
#

' public void OnTriggerEnter(Collider other)
{
if (other.tag=="Player")
{
Vector3 direction = Vector3.right;
Ray theRay = new Ray(rayStart.position, rayStart.TransformDirection(direction * range));
Debug.DrawRay(rayStart.position, rayStart.TransformDirection(direction * range));

        if (Physics.Raycast(theRay, out RaycastHit hit, range))
        {

            if (hit.collider.tag == "Ground")
            {
                //Debug.Log("cant spawn");
                bx.enabled = false;

            }
         
           
         }
        else
        {
            Instantiate(groundCube, RBspawnPoint.position, RBspawnPoint.rotation);
            //bx.enabled = false;
        }
} '
languid spire
#

so how do you parent your enemies to the ground?

sage spruce
#

they are on the ground prefab ready to attack

#

as a child onject

#

object

eternal falconBOT
#
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.

languid spire
#

ok so you are only working with the prefab, never with the GameObject created from the groundCube prefab

sage spruce
#

thats right

languid spire
#

no, thats wrong, that is why your enemies are dead when you instantiate again because you are instantiating the same object which you just used

sage spruce
#

@languid spire thanks for the help, at least now i know I am doing it wrong. I will try to find a solution

languid spire
#

Solution is easy

#

GameObject groundGO = Instantiate(groundCube, RBspawnPoint.position, RBspawnPoint.rotation);
then use groundGO in the rest of your code instead of groundCube

sage spruce
#

thanks Steve I will implement it right now

sacred zenith
# short hazel Returns an array of colliders

Just tested, it returns only one collision per collider. Say I am checking the ground and want the coordinates bellow something, the box will only return one coordinate of Terrain

tender stag
#

and make it better

#

or does it look fine?

ivory bobcat
#

That's 65 lines. What're we supposed to look at?

tender stag
#

there is a lot of repetition

#

whole method

#

i feel like its too long

#

for what its actually doing

main flame
#

17 to 36 is weird

#

You're checking the same things in reverse order?

tender stag
#

yeah

ivory bobcat
#

You could probably refactor it for readability else opt to not create a new instance of the list or create it with a set capacity to avoid garbage collection etc

tender stag
#

so an object that has slots

main flame
#

nvm yeah

tender stag
#

and if it does you first add those slots to the list

crude prawn
#

instead of GUIText.pixelOffset what can i do?

acoustic arch
#

for an fps should the bullets be invisible and have them shoot from the camera?

#

or visible and make the crosshair accurate to where the gun is pointed

tender stag
#

depends what you want

acoustic arch
#

which is better

tender stag
#

there is no better

acoustic arch
#

for a simple game from camera is probably better

tender stag
#

if you want physics bullets

#

then go with them coming out of the gun

#

and using physics

#

if not its prob better to use a raycast from the camera

acoustic arch
#

yeah

sacred zenith
#

In this image, assuming this is all on 3D space. The red is my vehicle, I have access to the BLUE dots coordinates. How can I find the Terrain coordinates of the GREEN cells?
I want to change the texture of those cells in specific

sage spruce
#

@languid spire I could not get it to work so I gave up on prefabs spawning prefabs (they just clone their curent state) , intead I have created a spawn manager that with a puplic function and the prefabs just feeds the next spawn point to the script and the manager spawns the prefabs. This works like a charm. Thanks again for the help

sullen lantern
#

void SaveData()
{
PlayerPrefs.SetInt("higscore", highscore);
int button;
if (buttonEnable)
button = 1;
else
button = 0;
PlayerPrefs.SetInt("buttons", button);
Debug.Log("Data Saved: "+button +", "+ highscore);
}

void LoadData()
{
    highscore = PlayerPrefs.GetInt("highscore");
    buttonEnable = (PlayerPrefs.GetInt("buttons") == 1);
#

I want to save int highscore and int buttons

rich adder
sullen lantern
#

yeah

rich adder
#

this isn't the entire script..
Anyway.
Try adding PlayerPrefs.Save after SetInt

sullen lantern
#

should I post the entire script

rich adder
#

did you read the bot message how to post script?

#

use website linked

jovial forge
#

Man, this concept of a prefab referencing in scene components just isn't computing

sullen lantern
rich adder
#

also what you should and shouldn't reference between what

rich adder
sullen lantern
#

sry

#

the entire code

rich adder
#

nvm

#

lol

sullen lantern
#

:)

rich adder
#

my firefox search being weird rn

#

wait yea

#

OnLevelWasLoaded() isn't called anywhere

#

therefore LoadData is never actually called

sullen lantern
#

but OnLevelWasLoaded was shown in Blue for me so I thought its a build in like Update and Start

rich adder
#

oh it is a monobehavior

#

never seen this b4

#

uhh

#

this is like unity 3.5

sullen lantern
#

2021.3.13

rich adder
#

why are you using such an old version

#

oh

sullen lantern
#

sry

rich adder
#

anyway this function doesn't seem to work or something

#

its old

sullen lantern
#

well

rich adder
#

use the SceneManager instead

sullen lantern
#

is there an alternative

rich adder
#

to subscribe to level changed

sullen lantern
#

so like which method

rich adder
#

also can do

        Scene scene = SceneManager.GetActiveScene();

        if (scene.buildIndex == insertSceneBuildIndexHere) {
        //Do something
        }
        if (scene.name == insertSceneNameHere) {
        //Do something
        }```
sullen lantern
rich adder
#

i thought you were on unity 3.13 lol

sullen lantern
#

oh ok

rich adder
#

your function is before unity 5 was a thing

#

thats like more than like 5-10 years now iirc

sullen lantern
#

ooooh

rocky canyon
#

u can duplicate ur entire project folder and rename it.. open the copy through the newest version or (newer) version of unity..

#

if it doesn't work on ur project u still have the original.. but yea ur missing out on so much new stuff πŸ˜„

sullen lantern
#

what can be new...

#

ima try it

rich adder
#

they're fine

rocky canyon
#

ohh i thought they were using pre- Unity 5 πŸ‘€

#

i was like whats NOT new

rich adder
#

their original msg said 3.13 lol and was presented with a function from unity 3.

rocky canyon
#

lol

rich adder
#

I put the two together wrongly haha but still they used deprecated function I didn't know existed on MB

rocky canyon
sullen lantern
#

I think I just accidentally deleted my Project...

rocky canyon
#

if ur on 2021 thats new enough

#

Ctrl + D?

sullen lantern
#

jeah

rocky canyon
#

its in ur recycling bin

sullen lantern
#

...

#

I ctrl + Z ed

rocky canyon
#

dont do that to urself

#

πŸ˜„

rich adder
#

good time to learn Version Control before going futher

sullen lantern
rocky canyon
#

Ctrl + C and Ctrl + V

#

is the safer bet

#

Ctrl + D is a unity thang

sullen lantern
#

someone at Unity really thought "lets change duplicate into delete XD"

rocky canyon
#

yea i think its a bad hotkey imop

#

once u get used to it.. its liable to screw u over in other programs

#

as D is delete sometimes

sullen lantern
rocky canyon
#

Shift + Del permanently deletes in windows

#

thast a real bad key.. thers no recoverying that

rich adder
#

everything is technically recoverable

rocky canyon
#

until it is re-written

#

but have you ever used a recovery tool?

sullen lantern
rocky canyon
#

theyre all trash

#

unless you buy one.. the free ones suck lol

rich adder
#

it should work

sullen lantern
#

ok

#

thanks

rocky canyon
#

u can still simulate android devices thru the editor

sullen lantern
#

I do

rich adder
rocky canyon
#

u can buy a pre-paid phone for cheap

sullen lantern
rocky canyon
#

less than 50 bux

#

that u can atleast test on

sullen lantern
rich adder
#

make sure its running at all

rocky canyon
#

oof, ^

rich adder
#

"doesn't work" isn't helpful

rocky canyon
#

do that.. make sure ur calls are being accessed

#

then go from there

sullen lantern
#

sorry

rocky canyon
#

Debug.Log("This Function got called properly");

#

or is it .log

#

its been a minute

rich adder
#

Log

sullen lantern
#

Debug.Log("THis Function doesnt work")

#

:L

rich adder
#

doesnt matter what u write for this one

rocky canyon
#

then the function isnt being called..

#

just make sure it prints something

tender stag
#

@ivory pollen sorry to ping you, but i've just realised that the error happens almost every time when im compiling InventoryManager.cs

sullen lantern
#

VS stopped working 😭

rocky canyon
#

restart, and try again πŸ˜„

sullen lantern
#

loads

#

so the method is called

rocky canyon
#

πŸ‘

sullen lantern
#

and it also logs data savedd

rocky canyon
#

make sure you have ur scene plugged into the build index of the project

sullen lantern
#

it is

rocky canyon
#

ok good, just thinking of the common mistakes

rich adder
sullen lantern
#

1 sec

rocky canyon
#

what doesn't work?

#

you say "Loaded" is called.. which makes sense.

#

but thers nothing in that function that actually loads a new scene

pseudo frigate
#

in a 2d project how to do you make things follow alongside the wall collider? like in this clip from an old NES game, the fireball follows the wall after hitting it. and also those little ball enemies follow along the wall as well

https://youtu.be/eMFg_BKZMzQ?t=1521

http://www.longplays.org

Played by: Reinc

When the world was still in a state of chaos, evil spirits roamed the world freely and rioted. The magic document "Key of Solomon" was the product of great King Solomon's magical research. It described how the evil spirits were confined to the underground constellation Miya. Centuries later, one man so...

β–Ά Play video
sullen lantern
#

When I call Die() the player reloads the scene and should load the highscore data but he doesnt load the highscore

#

its set to 0

rocky canyon
rich adder
#

and when

#

make sure you have data also

#
 void LoadData()
    {
        Debug.Log("Loaded");
        if(PlayerPrefs.HasKey("highscore")){
            Debug.Log("Has Highscore saved");
        }```
#

eg

sullen lantern
rich adder
sullen lantern
#

every time the scene reloads

rich adder
#

and you checked the if statement I sent you

#

PlayerPrefs.HasKey("highscore")

#

see if the value is there so you know thats not the problem

sullen lantern
#

Im testing

#

SO...

#

it still skips to zero when I reload the scene

rich adder
near saddle
#

how come when i use cinemachine 2d all my gameobject sprites disappear

proud vigil
#

Alright thx, i deleted it!

rich adder
near saddle
#

it is

rich adder
#

is the new camera somewhere else?

near saddle
#

b4 i added it i can see the gameobjuects nd stuff

slender nymph
rich adder
sullen lantern
rich adder
sullen lantern
#

yeah

#

Debug.Log("Loaded");
if (PlayerPrefs.HasKey("hightscore") && PlayerPrefs.HasKey("buttons"))
{
Debug.Log("Has Data");
highscore = PlayerPrefs.GetInt("highscore");
buttonEnable = (PlayerPrefs.GetInt("buttons") == 1);
}

rich adder
#

OH FFS

#

strings

sullen lantern
#

strings?

short hazel
#

hightscore

sullen lantern
#

...

rich adder
short hazel
#

Misspelled in the if statement

sullen lantern
#

:(

rich adder
short hazel
#

Misspelled everywhere :/
Use a const string variable !

sullen lantern
#

hate grammar

#

:(

short hazel
#

const string Highscore = "highscore"; and then the compiler backs you up

rich adder
sullen lantern
#

it works now

#

😭 😭 πŸ’€

rich adder
#

idk how I didn't see that earlier lol

short hazel
#

Type it wrong, and you get an error in the code directly. Change its value, and it's reflected everywhere. Absolute win to use const in this case

sullen lantern
slender nymph
sullen lantern
#

since like two days

#

thanks yall

near saddle
#

ty

sullen lantern
#

I want to change my script so I can call Save Data and Load Data without having a Player Movement script appended

#

is that solved with static classes?

slender nymph
#

not necessarily. if your Save and Load methods are on the PlayerMovment script then you need to move them to some other class. depending on your needs it could be an instance in the scene, a scriptable object, a static class, there are many ways to go about it

sullen lantern
#

is it possible without a gameobject carrying the script

#

like I want to call it in every scene

slender nymph
#

"instance in the scene" would be the only option i suggested that requires it to be attached to a gameobject

sullen lantern
#

oh

slender nymph
#

of course that still doesn't preclude it from being accessible in every scene

sullen lantern
#

So like when I use a static class how would I do this?

slender nymph
#

why not go find a tutorial to follow?

sullen lantern
#

sry

#

often times this is faster and creates less confusion#

slender nymph
#

that's really only true if you are only watching terrible tutorials that don't explain the process and just basically dump code on you instead

sullen lantern
#

most of them are like this

lean temple
#

Hi! I am very new to unity and started like 5 days ago. Im workin on a Gorilla Tag fangame using XR. Lately ive been getting this error called β€œ A native collection has not been disposed, resulting in a memory leak. β€œ can someone please help me? Im scared i might lose my project.

wintry quarry
#

You're not going to lose your project

#

You should be using version control to prevent any unexpected data loss though

#

I.E. Git

#

That error is quite generic and unless you're dealing with the Job system or DOTS it's not related to your code

lean temple
#

Ok tysm and im gonna see if it helps

spiral rain
#

I have this problem. Basically I am trying to set the position of a object that I instantiated but it is not going where I want it to I tried local and world position but both seem to have the wrong x value and y value here is the code snipit that makes and sets the position ``` for (int i = 0; i < PlayerInventory.i.Soc.Count; i++)
{

        currentButton = Instantiate(ButtonTemp, parent.transform);
        if(xpos < 556.2f)
        {
            xpos += 188.2f;
        }
        else if(xpos >= 556.2f)
        {
            xpos = -571;
            ypos -= 170;

        }            
        currentButton.transform.position = new Vector3(xpos, ypos);
   }```
wintry quarry
#

Also is this a UI element?

#

You should be using the recttransform layout system to position your UI elements, not setting the position in code directly

spiral rain
opaque mortar
#

i have got this error Assets\scrips\PlayerMotor.cs(5,14): error CS0101: The namespace '<global namespace>' already contains a definition for 'PlayerMotor'
can someone help

languid spire
opaque mortar
#

i do not i cheked

languid spire
#

bet

summer stump
opaque mortar
#

look

summer stump
#

If you show one folder, I will tell you it could be in a different folder

opaque mortar
languid spire
#

it could even be in a completely unrelated script

summer stump
#

Or a different script, as Steve said

#

Look through your scripts for PlayerMotor

#

Search using the IDE

languid spire
#

<@&502884371011731486>

opaque mortar
summer stump
#

They... can see deleted comments btw

opaque mortar
#

ok well bye

summer stump
opaque mortar
#

i gess

opaque mortar
summer stump
opaque mortar
#

yes

summer stump
opaque mortar
#

can i cal you be ezay

#

for me

summer stump
opaque mortar
#

ok

#

it start when i change my code

summer stump
#

You gotta just learn to google things. If you don't know what an IDE is, google it.
If you don't know how to search in it, google it.
You will find all your need. I pointed you in the right direction, and Steve told you the answer/reason for the error
You have another PlayerMotor. Find it

slender nymph
opaque mortar
opaque mortar
#

and fn and rl and on mc severs

slender nymph
#

congrats. did you know that you are breaking the TOS for most of those services? but that's off topic from here. you should probably leave this server until you are old enough to even use discord

swift crag
#

i remember having to stop using the Gruntz! fan-forums because I was 12

#

or maybe 11, i forget

#

is there a more clever way to make a bidirectional map than to just have two dictionaries?

#

i guess i can just make a little class

polar berry
#

hey guys I dont know were is the best way to post for this, but my update start or any trigger enter are in gray, the compiler is ignoring them and I have this error when I hove with the mouse "Private member 'NewBehaviourScript.Start' is unusedIDE0051"

#

any ideas?

swift crag
#

Does the class derive from MonoBehaviour?

#

i.e. does its first line look like public class NewBehaviourScript : MonoBehaviour

polar berry
#

yeah

#

I am not new to this

wintry quarry
#

does the code run?

polar berry
#

no

wintry quarry
#

Show your code

polar berry
#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{
    // Start is called before the first frame update
    private void Start()
    {
        print("Hello World");
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
wintry quarry
#

looks fine. If the code isn't running you haven't attached it to an active GameObject in the scene.

#

if the IDE isn't recognizing those as unity messages, it's not configured properly for use with Unity

polar berry
swift crag
#

we are attempting to help you.

wintry quarry
#

Show it and show your console

polar berry
polar berry
wintry quarry
#

of your inspector, of the console

#

maybe just the whole editor window in play mode with this script attached to an object in the scene

polar berry
swift crag
#

info messages are disabled.

#

turn them on (and then fix your IDE)

polar berry
#

lool

#

yeah its there

#

the hello world

#

omfg

#

I feel ashamed

#

thanks

#

I was used to the warning messages to be there already

tender stag
#

since when can you do print

#

is it the same as debug.log?

wintry quarry
#

it literally just calls Debug.Log, yes

tender stag
#

bruh

wintry quarry
#

it's to make python people more comfy

tender stag
#

didnt know

slender nymph
#

it only works for the single parameter overload of Debug.Log though

tender stag
#

oh

#

alright

#

easier way to write this?```cs
foreach(var cell in hotbarCells)
{
cells.Add(cell);
}

foreach(var cell in inventoryCells)
{
cells.Add(cell);
}```

wintry quarry
tender stag
#

alright thanks

wintry quarry
#

or

List<InventoryCells> cells = hotbarCells.Concat(inventoryCells).ToList();```
(with `using System.Linq;`)
queen adder
#

Does anyone have a script for a 2d.mobile game that lets you move side to side

summer stump
#

What part specifically are you struggling with

swift crag
#

not posting the same question in four different channels, it appears

summer stump
lone sable
#

What would be a good way to keep track of a bunch of stats? I'm talking about things like.. "Used a weapon X amount of times" or "Died to X this amount of times" or even things like "Saw NPC X amount of times". I guess a generic way to track things? Obviously, I don't want to use PlayPrefs, so I'm trying to think of a generic solution where in editor, I can define the key etc? Iunno. Thoughts?

timber tide
#

any variable which you can add to

#

add it with your player scripts and append to it

lone sable
#

Sure, but mroe so an overarching system.

I think I stumbled on the Termanology which is called Blackboard.

timber tide
#

No clue with termanology of the stuff, but what you want is basically just a struct.

#

if you have like say multiple players, then perhaps some singleton via gamemanager, but even then just stick it on the players and access it

swift crag
#

You need to decide how you're identifying each stat

#

Maybe enums, maybe just a bunch of constant string keys

lone sable
#

Yeah, thats kinda what I'm trying to figure out. Whats the best way to track the things I want to track, and how to go about tracking them.

I guess I'm looking mostly for design priciples. I assume this has been done in the past.

swift crag
#

I was dealing with the same problem a few months ago

#

Didn't really "solve" it, per se

timber tide
#

I'd just cache it all honestly

swift crag
#

I wound up storing each kind of stat separately (floats and ints)

#

and using enums to identify them

#

Enums are annoying because they'll go haywire if you rearrange them. Assigning explicit values fixes this

timber tide
#

I guess if there is a lot of stuff you want to keep track, then perhaps some string/value dictionaries

#

if the purpose is to just display it to the user

swift crag
#

As for storing the data: just use Json.NET to serialize a dictionary, if you go with a dict

lone sable
#

There will be events fired from said values as well, pending whats going on.

swift crag
#

oh, this isn't strictly stat-tracking

lone sable
swift crag
#

you want to have reactions to these

lone sable
#

Correct. Mixture of both really?

swift crag
#

In that case I'd say you should make a class that holds a delegate for every kind of stat

#

so that you can subscribe and unsubscribe

#

If you want to do stats per-item (e.g. "kills with X" and "times Y used"), you might want something smarter than just a big blob of string keys

lone sable
#

The idea being is like. If a player steps on a spike trap, say, every 10 times, then they should say something about it. Or, say on the 10th attempt of a boss, a cutscene happens. But then also, I want thinks like generic stats like you've died to this enemy X amount of times" etc.

swift crag
#

I mean, you could totally do $"stat-{weaponIdentifier}-{statKind}"

timber tide
#

problem is unique stuff and how much you want to display that

swift crag
#

but i might lean towards something more polymorphic

timber tide
#

like how are you deciding between two different instances of an iron sword you killed with. In this case, either merge the kills together, or add the higher of the two.

swift crag
#

so a Stat could be a SimpleStat, that's just a string key

#

or an ItemStat that holds a reference to an item kind along with which item stat it represents

#

the idea being that you could construct an ItemStat as needed to look up "number of kills with X item"

#

You'd just need to override GetHashCode so that the same item and the same stat always gives the same code

#

then it'd work nicely in a dictionary

lone sable
#

Hmm.

swift crag
#

but it would survive a weapon rename

#

well, you would ideally avoid changing the identifier if you were using string keys

#

you'd just change the display name if needed

timber tide
swift crag
lone sable
#

Well, I already have SO's tied to all of my enemies, weapons, and a few other things.

I could easily tie a "Key" to them to use for keeping track of stuff.

#

Then from there do sort of what you are saying, so, using playprefs as an example (Dict Json instead)

PlayerPrefs.SetInt(weaponID-TimesEquiped,value)
or
PlayerPrefs.SetInt(enemyID-DiedTo)

etc.

swift crag
#

If you need a unique identifier for each SO asset, you could just copy the asset GUID into a field on the scriptable object

timber tide
#

Did you want to use playerprefs? I thought you didn't want to.

swift crag
#

It's a little funky (you have to make your own serializable GUID)

lone sable
timber tide
#

Ideally, just use non-unique cases, this way you can just use the SO IDs when possible.

lone sable
#

And even then I can have a enum system setup for the events I want to listen for, which, probably is a decent idea.

timber tide
#
// Get the asset path of the Scriptable Object
string assetPath = AssetDatabase.GetAssetPath(this);

// Get the GUID of the asset and set it
storable_ID = AssetDatabase.AssetPathToGUID(assetPath);

For the asset ID

lone sable
#

So building out the StringDict would be like.

weaponID + Stats.Equiped

#

or even enemyID + Stats.Killed

#

(I think thats what I'll do, keep it simple/small).

I can still hook up some sort of events to it as well.

barren loom
timber tide
#

how do I even type it

#

lol

lone sable
#

```csharp
//CodeHere
```

timber tide
barren loom
#

ohh, thank you

ivory pollen
silent valley
#

How can i get the sword sprite to always point in the direction the player is facing. aka the mouse? I spawn it in as a prefab so dont have it equipped to the player but to a weapon holdster. hope that makes sense

pseudo frigate
#

in this short clip, https://streamable.com/na3c7p , you can see in the first character jump he doesnt make it all that far, but if i spam attack while hes in the air he can travel a lot farther before touching the ground. i tried to make it so the gravity and velocity are 0 while the animation is playing with the intention of having the character temporarily freeze in place, i dont really want them to travel more. what do i need to do to fix the code?

void Start()
{
    rb = GetComponent<Rigidbody2D>();
}

void Update()
{
    // Get input in Update
    moveHorizontal = Input.GetAxis("Horizontal");

    if(moveHorizontal < 0)
    {
        movingLeft = true;
    }
    else if(moveHorizontal > 0)
    {
        movingLeft = false;
    }

    SetAnimation();

    // Jumping
    if (isGrounded() && Input.GetKeyDown(KeyCode.Space))
    {
        jump = new Vector2(rb.velocity.x, jumpForce);
    }

    if (Input.GetKeyDown(KeyCode.Mouse0))
    {
        Attack();
    }
}

void FixedUpdate()
{
    if (attackLeftRenderer.enabled || attackRightRenderer.enabled)
    {
        //rb.velocity = new Vector2(0, rb.velocity.y);
        rb.velocity = Vector2.zero;
        rb.gravityScale = 0f;
        return;
    }
    else
    {
        rb.gravityScale = 2.5f;
    }

    Vector2 movement = new Vector2(moveHorizontal * moveSpeed, rb.velocity.y);
    rb.velocity = movement;

    if (jump != Vector2.zero)
    {
        rb.velocity = jump;
        jump = Vector2.zero;
    }
}
slender nymph
#

you're resetting the effect of gravity back to 0 every single time you attack. gravity is an acceleration so it continuously increases the magnitude of the velocity.y. each time you attack you set it to 0 so it has to start over once the attack has been completed therefore allowing you to stay in the air longer

queen adder
summer stump
timber tide
silent valley
#

I would of thought it would be similar to my shotgun bullet spray as i rotate the sprite for that depending on my mouse - the projectile

pseudo frigate
timber tide
#

Oh, if you got a working methods then try it out. There's possibly otherwise to do this, but I'm just giving the general idea.

slender nymph
pseudo frigate
#

ill try that, thank you!

slender nymph
#

of course that will allow you to continue rising if you attack before the peak of the jump so if you don't want that to happen you'll need to check for that as well

queen adder
timber tide
#

Ah, is there a 2D lookAt?

slender nymph
#

no. you just assign either transform.right or transform.up to the direction

timber tide
#

oh yeah I guess that makes sense

summer stump
silent valley
slender nymph
#

i don't know what you tried or really most of the context of your issue

silent valley
#

my sword is always facing up. it doesnt rotate with the player.

#

I'm spawning a prefab which is where I'm getting confused. I have it so it spawns on my player but cannot get it to swing in the direction the player is facing

slender nymph
slender nymph
silent valley
#

I'm aware the move towards is wrong. I had it really messy but this is kinda what i was working with

#

using my shotgun bullets as referency - the shooting

slender nymph
#

well for starters, you only ever change its rotation one time

#

so it will be rotated in whatever rotation the player has when this originally spawns and then never rotated again. unless something in the hierarchy is affecting the rotation, but since you haven't bothered showing how your hierarchy is setup i can only assume nothing is rotating it

silent valley
#

I wouldnt say i'm not bothered

slender nymph
#

and which object in that screenshot has the component you shared the code from?

silent valley
#

The code is on my sword prefab which spawns whenever I press my mouse button. i'll show it now

#

it spawns on the FirePoint transform

slender nymph
#

i see that you give it the FirePoint's position. but is it actually a child of that object?

silent valley
#

yes. The "Dir" is a bit infront of my player.

slender nymph
#

please show the entire hierarchy during runtime when you expect this object to face whatever position it is not currently facing. these screenshots where the actually important context is either not provided due to not being in play mode or is cut out because you decided to crop the hell out of it is not helping

#

you'll also need to confirm that you have frozen the rotation on the rigidbody so that physics is not affecting the rotation. and check any animations you have to ensure those are not also affecting the rotation

silent valley
#

well....... It was my animation. fml.

#

thank youu

pseudo frigate
#
    void DestroyBlock(Vector2 pos)
    {
        pos.x = Mathf.Round(pos.x) + 1;
        pos.y = Mathf.Round(pos.y);

        Debug.Log(pos);

        if (Physics2D.OverlapBox(pos, Vector2.one / 2f, 0f, destructibleMask))
        {
            Vector3Int cell = destructibleTiles.WorldToCell(pos);
            TileBase tile = destructibleTiles.GetTile(cell);

            if (tile != null)
            {
                destructibleTiles.SetTile(cell, null);
            }
        }
    }

i have a 2d tilemap and had to put a tilemap collider2d and composite collider 2d on it to fix an issue where the player collider was getting stuck on it. but with the composite collider the code above doesnt work to destroy individual blocks, is there something i can change so i can still destroy an individual block but use the composite to avoid the stuck issue?

empty juniper
#

i have a plane that shoots and it used to work correctly but i decieded to delete the prefab and recreate it and it shoots until the bullet object in the hierarchy gets destroyed by going to far away and if i delete the gameobject it doesnt shoot

#

anybody know why this might happen

slender nymph
#

it sounds like you're cloning the bullet object that is in your scene instead of a prefab

empty juniper
empty juniper
lone sable
#

Whats the proper way to return T?

public T GetValue<T>(string key) {
        if (typeof(T) == typeof(int)) {
            Stat stat = blackBoard.FirstOrDefault(stat => stat.key == key);
            return (T)stat.intVal;
        }

        return default(T);
    }
crystal cipher
#

i think you should return as int

abstract finch
#

Is there a Mathf function that allows me to lerp a float starting in a way that starts off really high then end slowly or would I need to use an animation curve?

cosmic dagger
cosmic dagger
unreal imp
#

sorry about the topic again and sorry for responding late, does that code cause them to be deleted in order from first to last? because I'm not noticing it, eg: eliminates random toilets leaving 9,12,20, etc.

ashen ferry
#

that Queue will fill up to max amount and afterwards oldest toilets ( whoever you enqueued first thru that method) will start to be Dequeued giving you reference and u destroy that

#

u cant do anything to random elements in queue even if u wanted

abstract finch
#

Is this a proper use of an animation curve to adjust the speed of a lerp?

            _currentStrength = Mathf.L(_currentStrength, endValue, currentSpeed);```
cosmic dagger
acoustic arch
#

when a method returns a value how do you use the value

#

like after using

#

return;

#

and what is the value

cosmic dagger
acoustic arch
#

can you give me an example

cosmic dagger
#
string name = GetName();
Debug.Log($"My name is {name}");

public string GetName() {
    return "RandomDiscordInvader();";
}
abstract finch
ashen ferry
#

I can give u equivalent using list if u want access random elements lol

cosmic dagger
ashen ferry
#

it looks aight tho but multiply timeElapsed with recoilSpeed that would make more sense

abstract finch
grim tulip
#

Uhhh question

#

For code I kinda don’t get how I’m reading it soooo

cosmic dagger
grim tulip
#

If u look at a code how would you read it?

#

Like it’s a person or something else

cosmic dagger
#

@abstract finch when t moves from 0-1, the anim curve will move from 0-1 as well but along the curve you created . . .

cosmic dagger
grim tulip
#

Ok I’m trying to write code

#

And whenever I write it always say’s I’m wrong

#

Sooo

#

I’ve been thinking instead of just writing something randomly and hoping for the best

#

Or using someone else code cause that’s weird

abstract finch
grim tulip
#

Why not understand it first and know what I have to say to it

#

Like what they need to know

#

Inorder for them to take action

cosmic dagger
grim tulip
#

I’ve tried but I just get lost in the sauce

cosmic dagger
abstract finch
#
{
  float timeElapsed = 0;
  float startValue = _currentStrength;
  float endValue = _currentStrength + recoilStrength;
  while (_currentStrength < recoilDuration)
  {
    float currentSpeed = recoilSpeed*_recoilCurve.Evaluate(timeElapsed);
            _currentStrength = Mathf.Lerp(_currentStrength, endValue, currentSpeed);
            timeElapsed += Time.deltaTime;
            yield return null;
 }
 timeElapsed = 0f;
 while (timeElapsed < recoveryDuration)
 {
  float currentSpeed = _recoilCurve.Evaluate(timeElapsed) *  recoverySpeed;
  _currentStrength = Mathf.Lerp(_currentStrength, startValue,  currentSpeed);
   timeElapsed += Time.deltaTime;
   yield return null;
  }
    }```

I can add notes to it if needed, to be honest i dont know what im doing here
ashen ferry
#

nah

unreal imp
#

oh sorry xd

grim tulip
#

I think I just fount a video I don’t get lost in

#

Someone test mehhh πŸ˜ƒ

deft yacht
#

since last night i got my 660 errors down to one πŸ₯² anyone have ideas?? πŸ₯Ί

cosmic dagger
# abstract finch yep one sec ill post it its quite long

here is an example. i'll look at your code right now . . .

_rectTransform.localPosition = Vector3.Lerp(_oldPos, _newPos, _animationCurve.Evaluate(percent));

percent is the normalized t you would normally have when using Lerp . . .

swift crag
#

you will often see t used as a parameter for something that blends between two points

#

ranging from t=0 to t=1

dull eagle
#

Hey, anyone got an idea why the scripts on my prefabs are not updating when changing values and saving in visual studio? I also have auto refresh enabled.

swift crag
#

I think the idea is that it's the "time" -- at time 0, you're at one point, and at time 1, you're at another point

#

You often see it in parametric equations, where it can quite literally be the current time

abstract finch
cosmic dagger
abstract finch
#

theres two durations recoil then the recovery fro mit

swift crag
#

since you often evaluate them with an elapsed time

abstract finch
cosmic dagger
#

okay, that makes more sense . . .

abstract finch
#

to elaborate on how it works, there is two parts of recoil the move up part and pull back down, the reason why im using a global variable is so that if the player shoots again during recovery it will cancel the whole thing and start a new

cosmic dagger
cosmic dagger
abstract finch
cosmic dagger
#

also, you used _currentStrength in the Mathf.Lerp method, that will change the value of a every time it's called, thus, creating a skewed effect . . .

cosmic dagger
abstract finch
cosmic dagger
abstract finch
cosmic dagger
#
_recoilCurve.Evaluate(timeElapsed / recoilDuration)
abstract finch
swift crag
#

normalization rescales something to fit in a fixed range

dawn sparrow
#

How can I prevent an object I instantiated during play from being destroyed on application exit?

swift crag
#

in this case, it remaps [0..5] to [0..1], which is what the Lerp function is expecting

cosmic dagger
swift crag
#

everything is destroyed when the game quits..

swift crag
cosmic dagger
dawn sparrow
#

I'm talking specifically about an inventory scriptable object which stores an array of item scriptable objects

At runtime I have an AddItem() fuction that instantiates a new scriptable object from a given item and adds it to the inventory

What happens when I exit the application is the scriptable object is destroyed

#

I want to preserve that object

swift crag
#

you can't. everything is gone.

#

what you can do is write some data to a file

#

and then read that data back when the game restarts

#

and use that data to reconstruct your inventory

cosmic dagger
dawn sparrow
#

I thought scriptable objects existed outside application instances tho

swift crag
#

they do not

#

You are probably thinking of how you can make assets out of scriptable objects

#

those assets get loaded and turned into objects

#

you can't just create new assets on the fly or something, though. that's all locked in when you build the game

dull eagle
#

Anyone got an idea why script values are not updating on a prefab variant whenever I make changes in Visual Studio and save? I have auto refresh enabled.

swift crag
#

Because they never do.

#

The values you see in the inspector are serialized in the prefab.

dawn sparrow
#

I'll look into a save system

swift crag
#

The field initializers in your script are used when the object is constructed

#

The values are then overwritten as Unity restores the serialized values

#

So the field initializer only matters when creating a new instance of a component (or when you reset a component)

dull eagle
#

So how can I change a value in visual studio and have the updated value work in play mode? Because whenever I debug the value it is never updated

swift crag
#

Show your code. I don't know what you're doing.

#

!code

eternal falconBOT
#
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.

polar acorn
dull eagle
#
using Assets.Scripts.BaseClasses;
using Assets.Scripts.Models.BaseClasses;
using UnityEngine;

namespace Assets.Scripts.Models.Bullets
{
    internal class ExplosiveBulletModel : BulletBase
    {
        public float ExplosionRadius { get; set; }

        public ExplosiveBulletModel()
        {
            Damage = 1;
            ExplosionRadius = 3;
        }
        internal override void SpecialEffect(PassiveEnemyBase enemyModel)
        {
            if (enemyModel.isActiveAndEnabled == true)
            {
                Debug.Log("ExplosionRadius = " + ExplosionRadius);
                enemyModel.ExplodeEnemy(enemyModel, Damage, ExplosionRadius);
            }
        }
    }
}

Changing the ExplosionRadius and saving, the script is attached to a prefab variant of bullet

swift crag
#

okay, so ExplosionRadius isn't serialized, since it's a property and doesn't have [field : SerializeField] on it

#

I would expect it to always be 3, then, unless someone else is setting it.

#

Perhaps someone else is setting it.

#

It does have a public setter.

dull eagle
#

I mean when I change it in VS to let's say 2 and save wouldn't the field normally update in unity?

polar acorn
#

This isn't a monobehaviour is it?

dull eagle
#

BulletBase is

summer stump
#

It has a constructor, isn't that not possible for a MonoBehaviour?

wintry quarry
swift crag
#

it's perfectly possible

#

it's just unusual

wintry quarry
#

also yes you shouldn't use a constructor

summer stump
#

Oh ok

wintry quarry
#

that should be Awake

swift crag
#

AFAIK the constructor will be run as usual

wintry quarry
#

it runs as usual, but not when you expect

#

in fact it may run multiple times, and it runs before any serialized data is populated

swift crag
#

right

dull eagle
#
using Assets.Scripts.BaseClasses;
using UnityEngine;

namespace Assets.Scripts.Models.BaseClasses
{
    internal abstract class BulletBase : MonoBehaviour
    {
        public int Damage { get; set; }
        internal abstract void SpecialEffect(PassiveEnemyBase playerModel);
    }
}

not much here to really see

swift crag
#

in this case, I would still expect it to work, since nothing serialized is being touched

summer stump
#

I thought I remembered a warning saying not to do it. Which I guess is explicitly saying it is possible, just not recommended haha

wintry quarry
#

script values are not updating on a prefab variant
This seems to imply you're talking about some field in an inspector?

#

Can you explain which field you're talking about here?

#

and where you're changing it? And where you're checking it at runtime?

dull eagle
#

The explosion radius field here, I'm chechkng it at runtime

wintry quarry
#

you're changing it where and when

dull eagle
#

In Visual Studio, it's never changing in the game

wintry quarry
#

when are you changing it in visual studio

dull eagle
#

Right now? XD

swift crag
#

as in, changing the values assigned in the constructor

wintry quarry
#

that's not going to affect any already created objects

#

you need to use Awake and not a constructor

swift crag
#

There are no serialized fields.

wintry quarry
#

if you do that, it will change at runtime

swift crag
#

Oooh wait, I get it

#

Those objects were already constructed.

#

Adding that to the list of reasons to not use MonoBehaviour constructors...

wintry quarry
#

or unloading the scene

#

yeah

#

long story short - don't use constructors for MonoBehaviours

swift crag
#

If you need to call a parent class's "setup" method as well as your own, add a virtual method called OnAwake or something

#

and call it from Awake in the base class

dull eagle
wintry quarry
#

or just make Awake virtual

#

and override it (and call the base)

swift crag
#

I've never used a constructor in a monobehaviour

swift crag
wintry quarry
#

use Awake

shell ice
#

I’m trying to make it where only my hands show up for me in vr but to others they see the full body how could I do that?

swift crag
#

is this VRChat

wintry quarry
dull eagle
#

Now the values are always 0 and 0 in the inspector

using Assets.Scripts.BaseClasses;
using Assets.Scripts.Models.BaseClasses;
using UnityEngine;

namespace Assets.Scripts.Models.Bullets
{
    internal class ExplosiveBulletModel : BulletBase
    {
        public float ExplosionRadius { get; set; }
        internal virtual void OnAwake()
        {
            Damage = 1;
            ExplosionRadius = 3;
        }
        private void Awake()
        {
            OnAwake();
        }
        internal override void SpecialEffect(PassiveEnemyBase enemyModel)
        {
            if (enemyModel.isActiveAndEnabled == true)
            {
                Debug.Log("ExplosionRadius = " + ExplosionRadius);
                enemyModel.ExplodeEnemy(enemyModel, Damage, ExplosionRadius);
            }
        }
    }
}
swift crag
#

run the game.

dull eagle
wintry quarry
swift crag
#

actually, you'll never see the values on the prefab, since it'll never get an Awake

#

you must look at an instance at runtime

carmine mist
#

How to keep an object as "visible" when partially obscured by obstacle?

swift crag
#

You usually give an object serialized fields with a default value that you can then override in the inspector.

dull eagle
#

Weird it looks like the bullets from the object pool have the correct values, but whenever the bullet hits an enemy it still uses the 0 value's that show up in the prefab variant

swift crag
wintry quarry
swift crag
#

if you're new to unity, you should be doing things in the most straightforward way possible

dull eagle
#

Well I know for a fact that I'm not changing the values anywhere in code besides the initial values

swift crag
#

store values in serialized fields. instantiate and destroy objects as needed.

dull eagle
swift crag
wintry quarry
#

pooling is fine

#

as long as you understand how it works

dull eagle
swift crag
#

of course, you should also be profiling to find out why it's lagging

dull eagle
#

Well I'm not done yet so I have to estimate for the future, rn it's hundreds, in the future prob will be thousands

swift crag
#

it'll be zero if your game doesn't work

dull eagle
#

The game works fine, I think it's just unity not wanting to update my values whenever I edit a script, even though it did all the time before

eternal needle
#

didnt really see too much convo above, if these are objects with complexity (physics or some custom logic) then you just wont be running this at all. Pooling only saves you from new'ing up a bunch of objects, not from them actually existing

swift crag
wintry quarry
#

you figured out how to use the debug mode in the inspector - time to learn to use Debug.Log and/or your IDE's debugger

swift crag
#

you should make sure that you aren't trying to call SpecialEffect on the prefab

#

rather than calling it on the instance of the prefab that hit the enemy

wintry quarry
#

yep that's probably the issue

swift crag
#

if you were using serialized fields instead of properties that get set in Awake, the prefab would have the values on it, at least

#

(although, it would still be wrong to be talking to the prefab instead of an instance in the scene)

dull eagle
cosmic dagger
wintry quarry
#

Convert to mp4

shell ice
#

wrong one this one^

random sand
#

Can you use IK with configurable joints?

shell ice
#

Idk how to fix this

wintry quarry
# shell ice *

Are you switching your render pipeline asset in a script or something

shell ice
#

dont thing so just clicked play was working before but I switched to this model and that happened

#

fixed the character turing pink but everything else is staying pink

swift crag
#

I wonder if this being VR matters at all

#

I would make a new scene and see how that behaves.

inner marsh
#
{
    public GameObject MainInventoryGroup;

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Tab)){
            gameObject.SetActive(!MainInventoryGroup.activeSelf);
        }
    }
}``` no errors show, but the inventory screen doesnt pop up when tab is pressed
swift crag
#

that would make the InventoryCheck turn off its own game object

inner marsh
#

its on a inventory manager

#

would it still turn off?

cosmic dagger
inner marsh
#

oh so instead of gameObect. replace that with said MainInventoryGroup?

#

ie

cosmic dagger
#

give it a shot . . .

inner marsh
#

alr

#

it works, ty

carmine mist
#

This is a question I'm having trouble describing, but its pretty much how to have object that I do visibility checks on behave as an obstacle for others but not for itself?

swift crag
#

so you want it to block raycasts that you shoot at other objects to decide if they're visible?

carmine mist
#

Yes, I have it setup so theres a normal wall that just acts a barrier and when you it blocks visibility. The objects that are visible change colour.

#

I want the objects that change colour to also act as a wall for other objects that change colour

#

But becuase they're all on the same layer ("objects that change colour") I don't know how to make it ignore itself as an obstacle

swift crag
#

you could turn off the collider before doing the check, then turn it back on afterwards

#

or you could use RaycastAll so that you get back a list of colliders

carmine mist
#

Okay I'll try

#

Thanks that worked!

deft yacht
#

bro does anyone have any idea what could be causing this?? πŸ₯Ί

wintry quarry
deft yacht
#

uhm it was missing so i installed the latest version of pro, i currently have only one error now πŸ₯²

#

earlier it was 161

inner marsh
#

so uh im tryna do sum where i unlock the cursor to go into inventory but then lock it when i press tab again and my mind is dying tryna work the logic out anyone have ideas mb for being so slow lmao

#
    {
        if (Input.GetKeyDown(KeyCode.Tab)){
            MainInventoryGroup.SetActive(!MainInventoryGroup.activeSelf);
            Cursor.lockState = CursorLockMode.None;
            if(invopen)
            {
                invopen = false;
                Cursor.lockState = CursorLockMode.Locked;
            }
            if (invopen == false)
            {
                invopen = true;
            }   
        }
    }``` what i got so far, unlockes the cursor at first then doesnt afterwords
ashen ferry
#

so just put Cursor.lockState = CursorLockMode.None in another statement

inner marsh
#

wym?

inner marsh
#

alr

ashen ferry
#

u can do same thing with 3 lines if (Input.GetKeyDown(KeyCode.Tab)) { invopen = !invopen; MainInventoryGroup.SetActive(invopen); Cursor.lockState = invopen ? CursorLockMode.Locked : CursorLockMode.None; }

abstract finch
#
float timeElapsed = 0;
        float startValue = _currentStrength;
        float endValue = _currentStrength + recoilStrength;
        while (timeElapsed < recoilDuration)
        {
            _currentStrength = Mathf.Lerp(startValue, endValue, _recoilCurve.Evaluate(timeElapsed / recoilDuration));
            timeElapsed += Time.deltaTime;
            yield return null;
        }```
Is there a reason why this is instantly snapping to the end value without lerping at all?
random sand
#

nvm

wintry quarry
cosmic dagger
ashen ferry
#

im not at pc but iirc animation curve can go beyond 1 might want to check if u didnt drag it around way beyond that

cosmic dagger
#

@abstract finchcs Debug.Log($"Time Elapsed: <color=cyan>{timeElapsed}</color> | Duration: <color=cyan>{recoilDuration}</color>");

random sand
#

can you use ik along with configurablejoints at the same time

abstract finch
tiny leaf
#

when I wanna do:

(myFloat > 0)

Should I use Mathf.Epsilon or -Mathf.Epsilon instead of 0 and why

abstract finch
ashen ferry
#

send pic of ur curve

cosmic dagger
cosmic dagger
ashen ferry
#

make so this thing maxes out at 1 and ur good to go, on both axis

cosmic dagger
slender nymph
#

that's also backwards. it will immediately snap to the end position then move away from it if they just reduce those values

ashen ferry
#

ye

violet topaz
#
public class shooting : MonoBehaviour
{
    public Transform firePoint;
    public GameObject bulletPrefab;

    public Camera cam;

    public float bulletForce = 20f;
    public float timeBetweenShots = 1f;
    


    public void Awake()
    {
        cam = Camera.main;
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetButtonDown("Fire1"))
        {
            Shoot();
        }
    }

    void Shoot()
    {
        GameObject bullet = Instantiate(bulletPrefab, firePoint.position, firePoint.rotation);
        Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
        rb.AddForce(firePoint.up * bulletForce, ForceMode2D.Impulse);
    }
}```  I'm trying to add time between shots so i can add customization to my gun but i don't know how
abstract finch
random sand
#

can i implement ik along with joints

cosmic dagger
abstract finch
#

its working now thanks!

sterile river
#

Yo guys! In my game I switch between 3D and 2D and now in the 2D view it still feels like 3D (see screenshot). I change it by setting the projection to either orthographic or perspective. I might adjust it by setting the rotation of the camera to 0 if I press the key but how do I access it? This is my code:

    {
        _cameraRotation.yaw += _input.x * mouseSensitivity.horizontal + Time.deltaTime;
        _cameraRotation.pitch += _input.y * mouseSensitivity.vertical + Time.deltaTime;
        _cameraRotation.pitch = Mathf.Clamp(_cameraRotation.pitch, cameraAngle.min, cameraAngle.max);

        if (Input.GetKeyDown(KeyCode.C))
        {
            use2DPerspective = !use2DPerspective;
            Camera.main.orthographic = use2DPerspective;

            if (use2DPerspective)
            {
                mouseSensitivity.horizontal = 0;
                mouseSensitivity.vertical = 0;
            }
            else
            {
                mouseSensitivity.horizontal = 0.2f;
                mouseSensitivity.vertical = 0.2f;
            }
        }
    }```
#

The camera keeps moving itself, also when I switch back to 3D

#

I'd be glad if you can help me out

random sand
#

how would you hold a weapon with an active ragdoll character? with a normal character i would use IK but idk how to do that with joints. any advice?

eternal needle
#

you wont have a super nice way of forcing them to stay in position, if this is something like 2 hands on a gun for example

random sand
prisma blaze
#

i want to spawn those spinning boxes on a plane, but i also want them to not be too close, so i wrote this function

    private bool IsCloseToAnotherBox(float x_dim, float z_dim)
    {
        var boxPosition = new Vector3(x_dim, 0.5f, z_dim);
        var colliders = Physics.OverlapSphere(boxPosition, 0.75f);
        foreach (var collider in colliders)
        {
            if (collider.gameObject.tag == "SpinningBox" || collider.gameObject.tag == "Player" || collider.gameObject.tag == "Wall")
            {
                return true;
            }
        }
        return false;
    }```
it works most of the time but there is still some overlapping, the dimensions of every box is 0.25 and the draw sphere is 0.75 so there shouldn't be any overlapping. the screenshot shows the gizmos with 0.75 radius
#

the parameters come from this function, it keeps generating random values until the function returns false

  private void SpawnSpinningBoxAtRandomPosition(GameObject plane, float x_dim, float z_dim)
    {
        GameObject obj = Instantiate(SpinningBoxPrefab, UnityEngine.Vector3.zero, UnityEngine.Quaternion.identity, plane.transform) as GameObject;
        var x_rand = Random.Range(-x_dim, x_dim);
        var z_rand = Random.Range(-z_dim, z_dim);
        while (IsCloseToAnotherBox(x_rand, z_rand))
        {
            x_rand = Random.Range(-x_dim, x_dim);
            z_rand = Random.Range(-z_dim, z_dim);
        }
        obj.transform.position = new Vector3(x_rand, BoxHeight, z_rand);
    }
gaunt ice
#

i hate var.... have you log the foreach loop and use comparetag instead?

eternal needle
# random sand that's what i'm doing right now, a joint from the hand to the weapon but it's ha...

what you want kinda depends how you want the game to feel. Like is this some game where shooting should be extremely accurate, or is it some goofy thing where the player just sprays around in whatever direction?
Maybe you can force the weapons rotation and make it kinematic? Honestly i was thinking of what to suggest and im blanking out because theres a lot of different stuff in here. Active ragdolls are more goofy/less accurate and weapons are supposed to be relatively accurate for a nice feel

prisma blaze
#

oh i didn't know compare tag existed

prisma blaze
random sand
#

what i'm thinking is instead of the hands holding the gun

#

the gun holds the hands up?

gaunt ice
#

first log the colliders.length , then log every gameobject in foreach loop (or use debugger)

prisma blaze
#

so they don't detect each other for some reason

#

nope the function returns true if it detects other colliders

#

maybe i'm wrong with the radius value?

#

even when they have .25 radius it still happens

eternal needle
# random sand the gun holds the hands up?

itll probably be fine that the hands hold the gun, at the end of the day you'll probably get the same affect from either one. I think you could just attach it via joint and constantly apply a torque to your gun to get it towards the correct rotation

gaunt ice
#

try overlap a large sphere after one box is spawned (put it outside the while loop, just overlap once), maybe cover the whole area, it must overlap the box

prisma blaze
#

but never boxes, even though they're closer than the wall

#

maybe i should try drawing box colliders instead? idk how to draw them though

frozen mantle
#

onTriggerEnter() and onTriggerStay() are not multithreaded/multitasked methods, are they?

gaunt ice
#

turn the radius of overlap sphere into 1000
just turn on gizmos then the collider will be drawn

north kiln
frozen mantle
#

okay, i seem to be having an issue where both are being called, but i call Destroy() in onTriggerEnter()

prisma blaze
#

could it be that unity instantiation takes more than 1 frame or something

#

but the function isn't running in Update

#

like can there really be nothing wrong with the function because unity hasn't created a box in that position yet, so the function returns false?

gaunt ice
#

are you overlapsphere wirh radius 1000 immediately after spawnine all box (no waiting) then is successfully logs all the box? idk how unity physics works

frozen mantle
#

i am trying to destroy the object as soon as it is picked up by the player if they are not on full health, but it seems that it stays around long enough for onTriggerStay() to be called, therefore giving me twice the intended healing amount

#

can onTriggerEnter and onTriggerStay called on the same frame?

prisma blaze
#

yes i overlapped a 1000 radius sphere after spawning

#

i think on triggerstay triggers 1 frame after enter. you can set a variable to check with, there might be a better option idk

gaunt ice
#

maybe try overlap a larger sphere while spawning (i have no idea why the sphere looks much larger than the box but it only overlapping the ground)

#

but once you overlapping a radius 1000 sphere, it works

prisma blaze
#

i really hope it's not a unity bug with my version

#

i doubt it but i can't think of anything

#

maybe i'll try spawning them disabled, and then try to put them in the plane properly and enabling them?

north kiln
#

If you're moving objects, those transform changes aren't immediately integrated, as that would be expensive. Calling https://docs.unity3d.com/ScriptReference/Physics.SyncTransforms.html would sync them in that case. If your call to Instantiate sets the position, I think that would set it before the new object is integrated. If you go through the transform afterwards, it won't update immediately.

#
  private void SpawnSpinningBoxAtRandomPosition(GameObject plane, float x_dim, float z_dim)
    {
        var x_rand = Random.Range(-x_dim, x_dim);
        var z_rand = Random.Range(-z_dim, z_dim);
        while (IsCloseToAnotherBox(x_rand, z_rand))
        {
            x_rand = Random.Range(-x_dim, x_dim);
            z_rand = Random.Range(-z_dim, z_dim);
        }
        GameObject obj = Instantiate(SpinningBoxPrefab, new Vector3(x_rand, BoxHeight, z_rand), UnityEngine.Quaternion.identity, plane.transform);
        // Redundant: GameObject obj = 
    }
prisma blaze
#

i was looking at the wrong function this whole time

#

i didn't think that the function not running in an update loop wouldn't make the changes immediately/on the next frame

#

i need to keep that in mind

prisma blaze
#

which function is better to subscribe to events, awake, onenable or start? or does it not matter?

strong wren
#

Generally Awake/Destroy or OnEnable/OnDisable. Consider whether the component can become disabled and how it should behave in relation to those events.

prisma blaze
#

thanks

languid spire
prisma blaze
#

should i use a lts release?

languid spire
#

Always unless you really know what you are doing or need something very specific

prisma blaze
#

got it, i'll install it soon

swift sedge
#

im still using 2021 lts, but there's no need to change so thats why im keeping it

prisma blaze
#

"if it ain't broken don't fix it"

languid spire
#

good plan, I still do a lot in 2019,4 and (mainly) 2020

swift sedge
#

some games like war robots (Pixonic) are still using 2017

languid spire
#

yep, I still have a lot of 5.6 and 2017, 2018 projects

random sand
#

how would you get the vector of direction needed to look at something

strong wren
#

Vector3 direction = (toPos - fromPos).normalized

keen dew
#

To look at something you need a rotation, not a direction

random sand
#
    {
        if (target != null)
        {

            Vector3 lookDirection = target.position - transform.position;


            cj.targetRotation = Quaternion.LookRotation(lookDirection);


        }
    }
#

would this work where cj is a configurablejoint?

prisma blaze
#

what's wrong here? i'm trying to get the textmeshpro components from ScoreText and ScoreValue

#

getcomponents in children returns a single component

#

i know i could use GetChild(0) but i want to know what's wrong with what i wrote

cosmic dagger
#

are they UI or 3d text?

#

also, do you get an error or what?

prisma blaze
#

they're just null

#

just ui

keen dew
#

and why are you using Find instead of serialized fields

cosmic dagger
prisma blaze
#

oh

prisma blaze
#

i should have probably looked that up first

cosmic dagger
#

use TextMeshProUGUI or just TMP_Text (works for both 3d and UI) instead . . .

keen dew
#

[SerializeField] private TMP_Text scoreText; and drag the object into the field

cosmic dagger
prisma blaze
keen dew
#

Both work but if you had the wrong type then obviously it won't work either way

cosmic dagger
#

it's cause you had the wrong component type, that's why it didn't work . . .

prisma blaze
#

i tried to use serialize field but when i dragged the component, i couldn't make unity focus on the object i wanted, hovering wouldn't change the inspector contents, dropping it there just added a new component to it

keen dew
#

You can lock the inspector contents with the lock icon

prisma blaze
#

how would i get the component then?

keen dew
#

open another inspector that's not locked

#

but doesn't really matter, just drag the object

prisma blaze
#

i didn't know you could do that lol

#

i just found the option

#

thanks

mossy arrow
#

what do i do when i lost date
how can i get it back

languid spire
mossy arrow
#

what is that!!!

#

what is cross post

dry tendon
#

does someone know why when i buid a project 2d for android the game look like it would have 30 fps? Its just a flappy bird... so the game its quite simple

languid spire
dry tendon
#

how can i increase them?

#

it looks horrible

#

The jump of the bird looks weird and not very fluid

keen dew
#

I doubt it's a frame rate problem. Frame rate doesn't/shouldn't cause changes in how objects move

dry tendon
gaunt ice
#

it will, the higher frame rate, the objects will move "smoother"

keen dew
#

If only the bird looks weird and nothing else then it's not a frame rate issue

#

other than maybe indirectly

dry tendon
#

all objects looks weird, but specially the bird...

#

So, i just need to create an script and paste this? ```cs
using UnityEngine;

public class Example
{
void Start()
{
// Make the game run as fast as possible
Application.targetFrameRate = -1;
// Limit the framerate to 60
Application.targetFrameRate = 60;
}
}```

#

and drag it for example into an object called fps controller

cyan horizon
#

apparently this makes u jump up higher if u hold down for longee, but how does it work?

#

also what button is ('Jump')?

gaunt ice
#

i remember the button is setted in project setting

cyan horizon
#

huh?

#

idk what the means if im honest

dry tendon
cyan horizon
#

so if the game was published would my selected input be the same for everyone else?

#

or would it vary depending on the other persons selected input

languid spire
dry tendon
cyan horizon
#

this is the whole thing

#

its basically from a character controller script

#

steve smith thanks for the help u helped me understand now

languid spire
dry tendon
languid spire
#

neither do I

dry tendon
#

but its said here

languid spire
#

well it's wrong. It's missing something absolutely crucial

languid spire
#

don't you see it?

#

what does a class need to have if the Start method is to be executed?

dry tendon
#

oh yeah

#

monobehaviour

languid spire
#

exactly

dry tendon
#

and that will work correctly?

languid spire
#

maybe, try it and find out

dry tendon
#

just one thing, why i would like to limit fps rate?

languid spire
#

conserve battery power, stop overheating for 2 reasons

dry tendon
#

true

#

thanks

north kiln
#

Stopping unnecessary hogging of the GPU. Often uncapped framerates will also cause unpleasant coil whine noises from GPUs

keen dew
#

30 fps is not janky so I'd be surprised if that solves the problem but if it does then great

languid spire
#

depends on how well/badly it's been implemented

#

@dry tendon One thing you could try is to limit your fps to 30 on your computer and see what happens to your game

dry tendon
#

thats exacly what i thougt

#

now i say you

#

ok, so

#

in my computer that limit works

#

now i'm gonna build it and see what it happens

silent idol
#

Sometimes the OnMouseDown/Up command work and sometimes they don't

#

although the scripts are very similar in both cases

#

Yes I have checked allignment and collider/trigger

grizzled wraith
#

i need help

#

on how i can have my particle system on play while the player is running

ashen ferry
#

how do u move ur player

swift sedge
ashen ferry
#

oh I was asking bloo how does he moves the player but actually it doesnt matter u should have running bool then u like

swift sedge
ashen ferry
#

var emission = urParticleSystem.emission;
emission.enabled = running; in update and it should work

short hazel
#

Particles systems have an emission rate over velocity module. Tweaked right, you shouldn't need to program anything in C# to make it work

ashen ferry
#

over distance yea I forgor

#

but he wants it when he is running

#

what abt walking

grizzled wraith
grizzled wraith
ashen ferry
#

then its just when moving and theres "rate over distance" in ur particle system

short hazel
#

Even if you have multiple walking speeds, you can use a curve for the emission rate

grizzled wraith
ashen ferry
#

it emits some particles per unit travelled kekW

#

never heard abt the curve where its at

grizzled wraith
grizzled wraith
short hazel
#

Aside the field where you input the value, there's a small dropdown where you can select between "single value", "random between two values", or "curve"

grizzled wraith
#

okay imma continue this after dinner

ashen ferry
#

oh dayum

grizzled wraith
#

ty, ur gonna make sum taiwanese exchange students happy

lone sable
#

I got a slightly weird problem? I'm trying to create a good ol' Singleton. This is the awake function for it:

void Awake() {
        Debug.Log("This first?");

        if (Instance == null) Instance = this;
        else Destroy(gameObject);

        DontDestroyOnLoad(gameObject);
    }

Then on another script I'm trying to call it OnEnable.

void OnEnable() {
        Debug.Log("Hello");
                Singleton.Instance.DoSomething();

The problem is, Hello comes out first? Its very weird? I also changed the ScriptExecution order for the Singleton to start sooner.

#

Any ideas why that might be happening?

languid spire
#

OnEnable executes before Awake, Also your Awake code is incorrect

short hazel
#

Awake and OnEnable run sequentially yes, it's not like Start and Update

#

But Awake is first

#

Not "all Awake", then "all OnEnable"

young warren
gaunt ice
#

same object awake->onenable->other object...

languid spire
#

Sorry I missed the 'Other script' bit

lone sable
ashen ferry
#

use Start if u want to be everything ready in other scripts I think

short hazel
#

Awake, initialize yourself. Start, get refs from others

lone sable
#

I spawn objects in at runtime via a pool. Some objects are in at runtime, others need to fire with OnEnable.

This is just the first time this is happening to me.

short hazel
#

That way everything will always be initialized at the time you start getting references from other objects

languid spire
#

Anyway the Awake is still wrong

lone sable
languid spire
#

Potential DDOL on a Destroyed object

ashen ferry
#

bruh I was looking at it and was thinking why as well the fact Destroy isnt "return" out of method still gets me kekW