#💻┃code-beginner

1 messages · Page 237 of 1

sharp bloom
cinder crag
#

🧷 Spring Script Paste
https://pastebin.com/4ZkbS9cw

📦 Project Files:
https://github.com/affaxltd/rope-tutorial

► Dani: https://www.youtube.com/channel/UCIabPXjvT5BVTxRDPCBBOOQ
► DaniTutorials: https://www.youtube.com/channel/UCn7E5qFz-BML6o7XnjtlytA

Hi, my name is Affax and I'm from Finland!
I'm an independent game developer who loves to ...

▶ Play video

ADVANCED GRAPPLING HOOK in 11 MINUTES - Unity Tutorial

In this video I'm going to show you how to create a precise grappling hook / grappling gun ability that you can use in any first or third person game! The ability is flexible, and can easily be used in combination with a swinging ability to provide lots of air control!

If this tutorial has...

▶ Play video
#

please someone help , im losing my mind ngl

polar acorn
sharp bloom
#

Somewhat unrelated tangent: I don't particularly like tutorials such as these where the guy is just saying "ok, so this is a little too complex to explain but just copy this"

swift crag
#

[pastes the entire source code of Minecraft]

sharp bloom
#

This just leads to situation where you are unable to fix anything yourself

#

I've been there

polar acorn
sharp bloom
#

Yup

swift crag
cinder crag
sharp bloom
# sharp bloom Yup

Basically you should be on top of this pyramid to know you've really learned something

#

I'm like in the middle somewhere

cinder crag
swift crag
#

but in the guys vid seems like it was working fine

well, we haven't seen what he did

#

you'll need to show us

polar acorn
polar acorn
#

If you're trying to set the third position of a line renderer with two points in it that's going to be an error

cinder crag
polar acorn
#

You'll need to check the error to find out which script and what line its on

#

because the screenshot did not provide any context

cinder crag
#

they are over here and the script is the grappling script

crisp token
#

Do you have to declare override in the header for c#?

swift crag
#

there are no "headers" in C#

#

and i'm not sure what you're referring to

crisp token
#

I see people writing stuff like public static override method

wintry quarry
#

that's the method definition

polar acorn
wintry quarry
#

also static override are never together

crisp token
#

Yeah

cinder crag
#

0, 1 , 2

wintry quarry
# crisp token Yeah

but yes if you want to override a method you have to write override, and also the method you are overriding must be virtual or abstract

crisp token
#

I’ve never heard of virtual before?

shell sorrel
#

its the other half of override

swift crag
#

well, the virtual keyword (along with abstract) is mandatory for using override!

#

any abstract method is implicitly virtual

shell sorrel
#

lets you mark a method as being overridable on the extending class

swift crag
#

and override is only used when your parent class defines a virtual method

crisp token
#

Ah, okay

#

Why is it so specific in c#?

#

Readability I guess

shell sorrel
#

what do you mean

wintry quarry
shell sorrel
#

C++ has very similar rules, its just divided between header and source file

#

where C# only has source files

swift crag
#

C# methods are non-virtual by default.

shell sorrel
#

also rather declare virtual, then have to declare final like java

polar acorn
crisp token
#

You don’t have to declare final in Java dk you?

shell sorrel
wintry quarry
crisp token
#

Oh

crisp token
#

I have a separate question. Let’s say you have a bunch of methods that will only ever be called in one class, but for the sake of organization you want them to all be declared separately in some different area. Would you use a separate class, class hierarchy, etc?

#

Defined*

shell sorrel
#

would just make them private methods of the class they are called in

polar acorn
shell sorrel
#

worst case make regions or just visually organize the code

cinder crag
polar acorn
crisp token
#

Yeah but if I have an already complicated class handling something like CPSR I’d prefer a separate area to have all the server checks I want to do on the received info

shell sorrel
#

if you classes are getting that big and comlicated maybe its doing too many things

#

and should be multiple purpose build classes or components

crisp token
#

It’s not big just complicated

shell sorrel
#

then whats the problem

shell sorrel
#

just clump them all togeather in the class that uses them then

crisp token
#

I iust feel like it’s bad practice but I guess not

polar acorn
shell sorrel
#

would say you are over thinking it, just solve the problem that needs to be solved and move on to the next task

#

feel creating a heiarhcy of classes just to separate out some methods that are call called in the same place anyways is more messy then just tossing them in where they are used and hides intent more

swift crag
#

at one point, I had a class that was easily over a thousand lines long that did everything for my game's main enemy

#

I decided the solution was to use partial classes, splitting the class definition across five files

#

It was awful. I could never find anything.

cinder crag
shell sorrel
#

@swift crag feel in that case i would use composition

swift crag
#

Bingo

polar acorn
cinder crag
#

and the error still appears

swift crag
#

I rewrote the entire game to be composition-based

crisp token
swift crag
#

everything is now an Entity with a Brain and Locomotion and Modules

polar acorn
#

Or the one you changed isn't the one you're referencing in the code

swift crag
#

Entity.cs is still 700 lines long, but it's just bookkeeping for the other systems (and a bunch of debug visualization code)

shell sorrel
#

also composition does not always mean components, it can be as simple as your MB instantiating a few regular C# classes to do other things within

swift crag
#

bonus: i can now play as any entity in my game

#

the original player, the enemy

#

a light switch

timber tide
#

composition to me means to just declare the variables even if you're not goingto use em

swift crag
cinder crag
#

the only thing im worried is on how do i make the rope have the animation since i have this in the grappling hook rope animation scriot

shell sorrel
#

like a character in my game, has a ton of components, that way stuff like managing its appearance, pathfinding, aniamtion, stats, avatar rendering in ui etc selecting what behaviours to run are all different components,

polar acorn
# cinder crag it is lol

Well, according to your log, the length of the list is 0, so at the time the code runs, there are zero points. Either you're setting the wrong one or it's becoming zero after starting the program

crisp token
#

Ok just let me paint this picture cause I feel like it really makes sense to have separate classes: I have a couple classes responsible for managing network time and sending, receiving, and verifying network states. (It’s just standard client prediction ). Instead of having a bunch of anti cheat checks all thrown into the class responsible for verifying, receiving, and sending states, why not have a separate class with flyCheck(), speedCheck(), combatCheck() etc…

cinder crag
shell sorrel
cinder crag
#

i maybe be blind cause i dont see it so idek

shell sorrel
#

like tend to have 1 class one purpose

sharp bloom
#

Wow I managed to send my objects to the shadowrealm

crisp token
#

Ik the sending receiving and verifying states sounds like a lot but just picture this class is like the overhead that manages these things

polar acorn
crisp token
#

It’s only 200 lines

shell sorrel
#

like a character at work, has 6 components, and maybe 10 or so regular C# objects in it for managing other things

ionic zephyr
#

if I have a prefabe with a serialize value which needs a script why can´t I assign it in the editor?

shell sorrel
#

the seperation has nothing to do with how much code, its with purpose and what depednencies are needed at what time

icy sluice
#
Vector3 dampingFactor2 = new Vector3(
    Mathf.Max(0, 1 - Damping2 * Time.fixedDeltaTime),
    Mathf.Max(0, 1 - Damping2 * Time.fixedDeltaTime),
    Mathf.Max(0, 1 - Damping2 * Time.fixedDeltaTime)
);
Quaternion CamDir = cameraTransform.transform.rotation;
Quaternion gunDir = gameObject.transform.rotation;
Vector3 acceleration2 = (((CamDir.eulerAngles - gunDir.eulerAngles) * Stiffness2) - Vector3.Scale(currentVelocity2, dampingFactor2)) * Time.fixedDeltaTime;
currentVelocity2 = Vector3.Scale(currentVelocity2, dampingFactor2) + acceleration2;
currentPos2 += currentVelocity2 * Time.fixedDeltaTime;

gameObject.transform.eulerAngles = currentPos2;

having a problem with rotations, if i could get some help?

cinder crag
polar acorn
cinder crag
#

i also found this still in the DrawRope func

ionic zephyr
cinder crag
ionic zephyr
polar acorn
polar acorn
ionic zephyr
#

an object with a component

#

but I cant

polar acorn
ionic zephyr
#

a slider which is in the actual scene

polar acorn
#

The prefab can exist anywhere. The scene object only exists in that specific scene

#

you'll need to set it after spawning in an instance of this prefab

ionic zephyr
#

and how could I assign it

#

by code?

polar acorn
#

With =, usually

ionic zephyr
#

but how should I reference that object?

polar acorn
#

Instantiate returns a reference to the thing it creates

ionic zephyr
#

what? sorry i dont understand

cinder crag
ionic zephyr
#

like what line of code should I write

#

and where

polar acorn
polar acorn
#

Something no longer having errors doesn't mean it's actually working as intended

cinder crag
#

im thinking but my brain fried , idk anymore

ionic zephyr
#

but this little objects are the ones I need to pass teh script onto

polar acorn
cinder crag
#

also the error doesnt go away

#

cant i use the drawrope func so the rope has the nice animation?

polar acorn
ionic zephyr
#

oh ok

#

sorry it was easy to understand

polar acorn
#

then, you can spawn the prefab with that script and use the returned reference to it to get the other objects you need

ionic zephyr
#

but should I create a new script with references?

cinder crag
ionic zephyr
polar acorn
#

A prefab can easily reference other things inside of itself

ionic zephyr
#

sorry I dont understand

#

I mean

ionic zephyr
cinder crag
#

daves and danis grappling hooks are a bit diff , danis uses joints but daves uses raycast. maybe is that a problem ig? idk i hope someone can help me with this problem

swift crag
polar acorn
cinder crag
swift crag
#

so how on earth do you hope to be able to smash together multiple slight variations of the same idea

polar acorn
#

At the very least, pick one and stick to it

whole idol
#

What are all these errors?

swift crag
#

did you just rename that file?

#

i've seen warning spam after doing that

swift crag
ionic zephyr
#

why do I get this

swift crag
#

because you're still trying to reference a scene object from a prefab

ionic zephyr
#

but how can I reference that object otherwise?

#

in a prefab

polar acorn
# ionic zephyr

Because either you changed the type of the object that field referred to, or your prefab is trying to reference a scene object

swift crag
ionic zephyr
#

Okay so I think I should explain all the context

swift crag
#
public class SomePrefab : MonoBehaviour {
  public ThingToConfigure configureMe;
}

...

SomePrefab instance = Instantiate(prefab);
instance.configureMe.someField = somethingElse;
summer stump
#

That is usually a good thing to do when starting to ask a question

polar acorn
cinder crag
polar acorn
swift crag
#

it's spelled with an "a"

cinder crag
#

Got confused

ionic zephyr
#

I am generating rooms with empty objects which group different gameobjects which depend on others objects by references

cinder crag
#

Welp there goes my cool idea of having a grappling gun with two modes

ionic zephyr
swift crag
#

"which depend on other objects by references" is extremely vague

polar acorn
swift crag
polar acorn
#

Use that reference to get access to the other things in the prefab

#

and set the variables on them

ionic zephyr
acoustic crow
#

Where can I find the Unity tutorial, is there a level?

swift crag
#

Okay, so whoever instantiates the prefab needs to have a reference to that slider.

eternal falconBOT
#

:teacher: Unity Learn ↗

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

acoustic crow
#

thanks brother

swift crag
#

by existing in the scene from the start

#

if it doesn't exist in the scene from the start, then someone needs to give it a reference

whole idol
#

how can I share this unity game file with a friend on discord for example?

ionic zephyr
swift crag
#

zip up the "Super Capsule" folder and send it

whole idol
ionic zephyr
#

it exists in the scene from the start

swift crag
polar acorn
swift crag
#

and assign the reference in the inspector

whole idol
#

I have to zip it first though right?

ionic zephyr
#

i cant

swift crag
#

Of course you can.

polar acorn
swift crag
#

It's part of the scene.

polar acorn
ionic zephyr
#

look

summer stump
#

Don't show a tiny cropped picture
Show the whole editor

polar acorn
# ionic zephyr look

you just said they're both in the scene at the start. Why can you not just drag it in

ionic zephyr
polar acorn
ionic zephyr
#

is the sldier

polar acorn
#

This is not what we are talking about

ionic zephyr
#

the room generats in the Awake

polar acorn
#

we cannot help you if you outright lie about what is happening

swift crag
#

Then who creates the rooms?

ionic zephyr
#

A gameManager in the awake

swift crag
#

Something must exist in the scene to instantiate the prefabs.

#

Okay, great. Give the GameManager a reference to the slider.

polar acorn
whole idol
#

They have to have Unity? Otherwise I can't send them a playable game file?

ionic zephyr
polar acorn
#

everything in your screenshot

wintry quarry
swift crag
polar acorn
ionic zephyr
polar acorn
ionic zephyr
#

but is there a way to access to that specific object inside of the prefab

polar acorn
#

that you said you did

ionic zephyr
#

the references are dragged

polar acorn
#

Make a script, put it on the base object of the prefab, and drag in the things you want

polar acorn
#

done

#

use those

swift crag
#

did you read the code that I wrote

ionic zephyr
#

yeah but i do no tunderstand it

swift crag
#

then ask questions about it instead of just silently ignoring it

#

what part of that code do you not understand?

ruby python
#

Evenin' all.

So I have a 'quadsphere' and some XML that I need to translate into a Shader (Not a shader question lol). The xml includes Lat/Long coordinates, would anyone have any idea (or be able to point me towards a resource) that would let me figure out how to apply/assign long/lat coordinates to my quadsphere? (not sure if I made any sense with that. lol.)

wintry quarry
#

XML shouldn't be involved in the quadsphere part

#

presumably you parse the data and then move on

ruby python
#

The quadsphere is a model, no coding involved. 1 sec.

swift crag
#

if the sphere's UVs are just a rectangular unwrapping, it should be trivial to go from coordinates to UVs

#

just remap latitude and longitude into the 0..1 ranges

ruby python
#

It's made up of 6 'faces' and then manipulated in my modeller to spherise it. So it has 6 'flat' UV's

swift crag
#

ah, it's a quadsphere, right

#

a subdivided cube

ruby python
#

!code

eternal falconBOT
ruby python
#

Parsing the XML isn't an issue, I know how to do that (xml structure below)

<Rule>
  <Layers>
    <Layer Material="OceanIce" Depth="20" />
  </Layers>
  <Height Min="0.0" Max="0.43" />
  <Latitude Min="0" Max="90" />
  <Slope Min="0" Max="1" />
</Rule>

It's more trying to figure out how to make use of the Latitude (assigning values to the QuadSphere)

wintry quarry
ruby python
wintry quarry
#

not asking anything

#

pointing you to the solution

ruby python
#

Not understanding what you mean then sorry.

swift crag
#

how is your sphere UV mapped?

#

assuming that you're trying to do something involving textures or the sphere's material

#

if not, i need to know what "assigning values" means

ruby python
#

6 faces (top, bottom, front, back, left, right). And yeah, the image I posted above is the sphere mapped with heightmaps for each face. I'll be creating a shader to colour the 'planet' based on the XML values and the heightmap.

swift crag
#

okay, so you need to write data into a texture

#

you need a method to convert from lat-lon to UV coordinates

swift crag
ruby python
#

Yeah, teh height and slope I can figure out how to parse/apply, it's the longitude value that I'm not sure about.

swift crag
#

I guess you could shoot a raycast at the sphere and get the UV coordinates from the hit.

cinder crag
#

does someone know how i can use the same key to change modes of the grappling hook? since rn im using F for swinging mode and G for normal mode and i wanna just use F , does someone know?

swift crag
#

instead of just setting the mode, check which mode you're in and set the other one

#
if (mode == Mode.Swinging) {
  mode = Mode.Normal;
}
#

e.g.

low path
#

could also use a state machine. input f = change mode. for each mode define the action taken by change mode

wintry nimbus
#

Hey, probably a beginner's mistake, but I'm having trouble with some errors. For a bit of context, this is my first 2D game where, for now, you can only move around, collect some points. I'm trying to add enemies, but those 2 errors comes up. I also sent the LogicScript, and the 2 scripts of points and enemies. Anyone knows where it comes from ?

swift crag
#

You can't declare two classes with the same name.

wintry nimbus
#

even the Start ? So how can I make it ?

polar acorn
swift crag
#

Start is a method.

#

target1script is a class.

wintry nimbus
#

oh right mb

#

Thanks

sharp bloom
#

With some trial and error

orchid trout
#

I am having a problem with unity's EventSystem. I have an element I want to re-select immediately after deselecting it. It's a text input field.
After onSubmit is called, I've tried to reselect the field but it keeps not getting reselected.

eventSystem.SetSelectedGameObject(gameObject); is what I am calling to try to select it.

I've tried calling this:

  • immediately after onSubmit is called
  • on Update
  • on LateUpdate
  • the next frame through a co-routine

but every time the field gets deselected because the field calls "DeactivateInputField" on itself for some reason

cinder crag
#

why does this error appear

orchid trout
#

Whats the correct way to reselect it? Its a text field element. I want it to act like any text field a chat engine uses like when I hit enter on my keyboard right now here on discord, the field remains selected and further keypresses continue to fill this field

safe root
#

!code

eternal falconBOT
wintry quarry
#

Also I'm assuming this is an enum, in which case that line makes no sense at all

#

I would expect something like:

if (currentMode == ChangeGrapplingModes.Swinging)```
safe root
#

I'm making a dash machine for my game and right now. My character only moves to the right and doesn't do the same to the left. No matter what it will head left. Does anyone know why?

https://gdl.space/maqakodoze.cs

orchid trout
wintry quarry
safe root
cinder crag
wintry quarry
safe root
swift crag
#

(IDeselectHandler requires you to implement OnDeselect, so this is roughly what Hambones suggested)

orchid trout
#

trying this now, if it also fails Ill try implementing that handling

swift crag
#

also consider

#

this will tell you if you're already attempting to set a selected game object

#

I'm not sure if that will be true whilst OnDeselect is running as the text field unselects itself

tribal minnow
#

hey guys, i need help with using play asset delivery.
normally my game is consisted of 3 scenes, but its size was somewhere around 1gb, so for me to upload it on google play store i need it to be less than 200 mb, for that i decided on using play asset delivery, i have this code right here that is supposed to download the asset bundles and then have 3 different functions for loading the 3 scenes, is it correct ? and if it is how should i do the build and how am i supposed to try it ?
https://gdl.space/soriqihawu.cpp

orchid trout
#

Oh that will be useful

    {
        if (reSelectOnSubmit)
        {
            eventSystem.SetSelectedGameObject(gameObject);
            reSelectOnSubmit = false;
        }
    }```
also forgot to add the i\f statement so that it doesnt always reselect
swift crag
#

watch out for infinite recursion there

#

select -> deselect -> select -> ...

orchid trout
#

It didnt infinite, it just didnt reselect 🤔

tribal minnow
orchid trout
#

I feel like I must be missing something because I cannot get it to reselect ever, not on update, late update, co-routine next frame

low path
orchid trout
#

scratch that, it does get called but not when expected

#

but it also doesnt work

low path
#

try implementing IDeselectHandler in your script

orchid trout
#

it doesnt get called OnSubmit, but it does get called when I click off of it, and even though the bool evalulates true, " eventSystem.SetSelectedGameObject(gameObject);" this simply doesnt work

low path
#

put it on the input field and define OnDeselect in the way you did "reselctonsubmit"

orchid trout
#

I think the problem is that eventSystem.SetSelectedGameObject(gameObject); is not how you select something in the event system

#

Ill try that handler next but if it still doesnt work I think that is the problem, because calling that line thusfar never selects no matter where/when it gets called

#

ill try changing it from gameObject to a more explicit reference to itself maybe?

wintry quarry
#

If it doesn't have a Selectable on it, that might be a problem

orchid trout
swift crag
#

ah, so it just errors on you if you try to do that!

#

good to know; i was a bit curious about that

orchid trout
#

changing it from gameObject to a reference to (myThing.gameObject) gave that error

#

before no error at all which wasnt useful

swift crag
#

I guess it just silently ignored your object that didn't have a Selectable on it

orchid trout
#

ah yeah it didnt

swift crag
#

I'd set a field when you submit and when you deselect

#

If you deselect after you submit, then reselect in Update

orchid trout
#

my code is being run in the script but hooking into the input field

swift crag
#

I bet the deselect happens in the same frame as the submit

#

in that case, you'd just check if both happened, then reset both bools to false

orchid trout
swift crag
#

I kind of wish selection worked on a Selectable, rather than a GameObject

#

I guess it could be ambiguous with multiple selectables on one game object

low path
#

honestly unity is nice in a lot of ways but ugui is a huge pita. i feel like i learned it a couple year ago and then somehow lost all knowledge...

#

i remember having an epiphany about anchors and positions and whatever and i have no idea how it works anymore

orchid trout
#

this DOES get called, but it doesnt select the field, and it doesnt give an error

#

and when I try to step into it, I cant for some reason

charred heart
#

hi! how can i enable baked navmesh in editor view?

timber tide
#

probably your gizmos in the top right corner there is off

orchid trout
#

trying tihs now

#

It says its selected, but its not selected

wintry quarry
#

just out of curiosity where is this eventSystem reference coming from?

orchid trout
charred heart
orchid trout
#

Maybe my understanding of 'selected' is whats flawed here

low path
#

i kind of doubt it

orchid trout
#

This is what I am trying to achieve without needing to reclick the field each time

orchid trout
#

I assumed that the input state that recieves inputs would be selected but I never tested that assumption and am not sure how to 🤔

timber tide
low path
#

you can probably also have a debug textbox that just periodically polls whatever values you're interested in

pallid verge
#

Dont they match?

orchid trout
low path
#

but i think you'll find that indeed, a textfield IS selected when you are inputting it

orchid trout
#

Yep

hot wave
#

I have a public int itemType; in the interactable code (to set as 1, 2 or 3), but it cant seem to relate with the dictionary in interactor or how to approach it rotationDictionary.Add(1, new Vector3(-30, 0, 0)); rotationDictionary.Add(1, new Vector3(-30, 0, 0)); rotationDictionary.Add(2, new Vector3(20, 0, 0)); rotationDictionary.Add(3, new Vector3(0, -10, 0)); I added a private Dictionary<int, Vector3> rotationDictionary = new Dictionary<int, Vector3>(); before void start, but i dont know how to make it work @-@ or if this is ok in update inside raycast but im not sure foreach (var kvp in rotationDictionary) { if (kvp.Key == itemType) { Vector3 rotationValue = kvp.Value; interactable.transform.Rotate(rotationValue); foundRotation = false; } }

low path
#

um... blinky line input field?

orchid trout
#

hm maybe I have to call something on the inputfield to set it to the blinky line up

orchid trout
#

I mean like any text field when you are able to type the bar blinks

#

even here in discord

#

which Im starting to think is a state separate to just being selected

timber tide
#

I remember running into that issue and I think how I fixed it was just not use select/deselect

#

and just appended directly to the text via input events

orchid trout
#

"inputField.ActivateInputField();"

#

this exists, ill try calling this

#

Yep that was it. I had to call ActivateInputField, not just selected UnityChanThink 🫠

#

the issue in the end was my assumption that being selected = input field active

low path
#

ugui shrugR

timber tide
#

more just tmpro having 10000 methods

orchid trout
#

I cant think of a use case where I'd want the field selected but not edit active, but I am sure someone somewhere needs it that way

#

Sweet I can move forward now at least, thanks for helping me debug 👍

timber tide
#

my word game I dont ever need to select/deselect it (should always be active) so my hacky way works for my requirements

low path
orchid trout
#

still helped, take the credit 🦆

cinder crag
#

i am not sure why the hell my character is still hanging in the air when the rope is gone , this only happens with the normal mode of the grappler

#

let me get a vid rq

weak zinc
#

does anyone know how to make random terrain generation? iam trying something, it kinda works but iam not getting the final thing i want, iam currently working at school project, i chose Survival game so iam trying to make great random generation

lost anvil
cinder crag
wintry quarry
wintry quarry
# lost anvil why is it when i call my static bool on my cameras zoom script, that it only zoo...

Think about it:

        if (isZoomed == true || interactZoom == true)
        {
            GetComponent<Camera>().fieldOfView = Mathf.Lerp(GetComponent<Camera>().fieldOfView, zoom, Time.deltaTime * smooth);
        }

        if (isZoomed == false)
        {
            GetComponent<Camera>().fieldOfView = Mathf.Lerp(GetComponent<Camera>().fieldOfView, normal, Time.deltaTime * smooth);
        }```
What happens when interactZoom is true, but isZoomed is false? Both of these blocks will run each frame.
neon ivy
#

I have a gravity direction, a vector3 of magnitude 1. and I'm wondering how to calculate the global direction of my movement which is a vector2. for a second I thought I just had to multiply but that sounds wrong. for instance if my movement is (0,1) so w is pressed and it should move forward and when gravity is (0,-1,0) so down. it needs to somehow apply a force of (1,-1,0) assuming no rotation and a g of 1. but when the gravity direction is (0,0,-1) the movement would be globally down so it'd need to be (0,-1,-1)... I think. I don't get this

polar acorn
cinder crag
wintry quarry
weak zinc
#

i need help, now it looks like its working, but i dont think this is usable as terrain for world

timber tide
#

unless you need predetermined trajectory, usually gravity just acts on the objects independently throughout your update loops

frigid flume
weak zinc
neon ivy
rich adder
timber tide
wintry quarry
#

I would think forward is either the direction your camera is facing or the direction your player is facing

#

Is this a 3d game?

neon ivy
#

yes

weak zinc
polar acorn
wintry quarry
# neon ivy yes

So you're walking on the surface of the sphere? Basically forward should either be the direction your player is facing, or your camera, or along the tangent of the surface you're standing on

#

you need to decide which

frigid flume
#

do you mean UpgradesInventory ?

timber tide
polar acorn
#

we mean inventory

rich adder
polar acorn
#

that's why we said inventory

weak zinc
rich adder
#

also whats up with NEWSCRIPT as a name lol

frigid flume
#

oh yes ok thanks

timber tide
# weak zinc ill try that, idk how to do it but i will try

Welcome to this series on procedural landmass generation. In this introduction we talk a bit about noise, and how we can layer it to achieve more natural looking terrain.

A quick summary:
'Octaves' refer to the individual layers of noise.
'Lacunarity' controls the increase in frequency of each octave.
'Persistence' controls the decrease in ampl...

▶ Play video
neon ivy
weak zinc
#

now its doing this , its too flat

timber tide
#

honestly pretty straight forward video, abit long, but it's as detailed as you're getting

rich adder
weak zinc
timber tide
#

can replace the noise map generator and grab fastnoise package and use that instead

pallid nymph
# neon ivy I'm just wondering how you calculate this. an uneducated guess was a matrix tran...

you get your camera (or something) forward, project on plane with normal being your up (that's minus gravity direction), then normalize - that's your sphere tangent forward... then you cross that with up and that's your right... then you multiply the horizontal input with the right and the forward input with the forward and that's your direction... and then there's the down which you add to that vector for gravity

weak zinc
neon ivy
# wintry quarry calculate what which part?

the input part of my movement vector.
so I have gravity which is simply multiplying the g value with the direction of gravity.
the input from the player and I combine these vectors to get the global velocity I should set rb.velocity to

wintry quarry
#

I mentioned three possibilities

neon ivy
#

I guess the direction the player is facing

#

cuz it's a third person game

#

movement is very important for this project so I'm just trying to understand and learn to get it right

frigid flume
neon ivy
#

I'm just a bit overwhelmed trying to do math I have no experience with xD

pallid nymph
#

direction player is facing sounds weird... unless by that we mean camera direction... if you're looking at the player from the side and press W, where does the player go? where the camera is looking or where the player is looking?

#

(do you have control over camera?)

rich adder
#

also why do you have two scripts do the same JSON utility saving

frigid flume
rich adder
frigid flume
#

they are form different scenes

neon ivy
frigid flume
#

i don't think anyone is a prefab

pallid nymph
rich adder
neon ivy
frigid flume
#

then how can i do it ? it was the purpose for me to use json

pallid nymph
frigid flume
#

i tried to use json to access data across scenes

rich adder
frigid flume
#

idk how to do another way

warm pawn
#

can somebody help me with this error code?
Animator.speed can only be negative when Animator recorder is enabled. Animator.recorderMode != AnimatorRecorderMode.Offline
UnityEngine.StackTraceUtility:ExtractStackTrace ()
ElevatorDoors:YouAreChosen () (at Assets/scripts/ElevatorDoors.cs:19)
UnityEngine.GameObject:SendMessage (string,UnityEngine.SendMessageOptions)
PlayerInteract:Update () (at Assets/scripts/PlayerInteract.cs:18)

code:https://hastebin.com/share/ixototicoq.csharp

rich adder
pallid nymph
rich adder
warm pawn
#

19 line is _Animator.speed = _f;
and i want it to be - since i want to play it backwards

rich adder
#

ah yes like Pulni pointed out, negative animator speed is not supported

#

Negative playback speed is only supported when the recorder is enabled. For more details refer to Animator.recorderMode.

rich adder
swift crag
#

Note that individual animation states can still run backwards

#

You just can't play the entire animator backwards

#

This would require it to actually run transitions backwards, which it can't do

pallid nymph
#

lazy animator... 😝

warm pawn
#

yea it just that thers 4 of them

#

less code

rich adder
#

I just duplicate the clip and put with -1 speed and call it a day lol

warm pawn
#

ok thx

#

yea i just wanted to know if theres a way

wintry quarry
#

if you want a Quaternion (which you can use to transform your input vector you can do:

Quaternion rot = Quaternion.LookRotation(forwrad, surfaceNormal);
Vector3 rotatedInputDir = rot * inputDir;```
neon ivy
#

if I'm not on a specific object but simply gravity is set to something other than down, can I just use that vector, multiply by -1 and input that instead of surfaceNormal?

neon ivy
#

ok cool

#

quaternions are scary but I think I can work with this

chrome wadi
#

Is it better todo that with a json or Xml file ?

    private void LoadDialogues()
    {
        string path = Path.Combine(Application.streamingAssetsPath, "Dialogues.json");
        Debug.Log("Pfad zur JSON-Datei: " + path);
        if (File.Exists(path))
        {
            string jsonString = File.ReadAllText(path);
            JSONObject dialogJson = JSON.Parse(jsonString).AsObject;
            foreach (var key in dialogJson.Keys)
            {
                JSONArray dialogArray = dialogJson[key].AsArray;
                string[] dialogLines = new string[dialogArray.Count];
                for (int i = 0; i < dialogArray.Count; i++)
                {
                    dialogLines[i] = dialogArray[i].Value;
                }
                dialogues.Add(key, dialogLines);
            }
        }
        else
        {
            Debug.LogError("Dialog JSON datei nicht gefunden " + path);
        }
    }
wintry quarry
#

Is it better to do what? Parse JSON? I would never try to parse an XML file as JSON

swift crag
wintry quarry
#

yeah and made the internals private

swift crag
#

you don't have to think about matrix algebra or quaternion arithmetic

#

you just use the Vector3 and Quaternion methods

chrome wadi
wintry quarry
neon ivy
neon ivy
#

my knowledge on them ends at them being a vector4

wintry quarry
#

all they are is a variable that holds a rotation

chrome wadi
wintry quarry
#

don't worry about anything else

wintry quarry
swift crag
#

e.g. Quaternion.AngleAxis(45, Vector3.up) gives you a rotation 45 degrees around the vertical axis

wintry quarry
#

(clockwise around it)

chrome wadi
neon ivy
#

oh so it's just a directional vector with 1 more float for axial rotation?

wintry quarry
#

don't worry about how it's represented internally

#

that's just one way to make one

#

look at all the functions in there

#

there are many ways to craft them

safe root
wild cobalt
#

I found a solution to the problem with overlapping events in the blend tree:

I found another solution to the issue with overlapping sounds when using blend trees which is to use the blend weights. The function that the animation event calls can take one parameter, which can be the animation event itself, so you can pass it into the step function and access the blend weights from there to get the audio to only play when it crosses a threshold.

How do I pass the animation event as a parameter?

swift crag
#

er, that doesn't show an example of it being received, though

#

you just accept AnimationEvent as the single parameter for your method

vapid void
#

// For a value type action.
// (Vector2 is just an example; pick the value type that is the right
// one according to the bindings you have)
var v = action.ReadValue<Vector2>();
} I was wondering how you use this, I was confused by the documentation

lost anvil
#

would it be a tween sequence?

swift crag
#

given an input action, this reads a Vector2 from it

#

that's it

#

are you unsure how you'd get an InputAction in the first place?

wintry quarry
safe root
vapid void
neon ivy
#

nice o: the difficult part for me is that due to the ideas I have for this game, there might be multiple gravitational forces working on an object xD so I need to calculate everything acting on an object and then set the rb.velocity to all of it combined xD gravity alone is already giving me trouble though xDDD

swift crag
#

if you want to read a vector2, then..read a vector2

swift crag
#

then you can just do that many times

edgy prism
#

Hello, I am working on some stuff for screen touch if I use IPointerDownHandler I can test with simulated touch screen but when I use input.TouchCount I cannot does anyone know how I can test input.TouchCount code on my PC?

rich adder
#

I could be wrong though

edgy prism
neon ivy
#

I got this

low robin
#

how do i trigger button click from code?

using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class ButtonClickWithRaycast : MonoBehaviour
{
public Toggle toggleActive;

void Update()
{
    // Check if Left Mouse Button is pressed
    if (Input.GetMouseButtonDown(0))
    {
        // Create a ray from the mouse position
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;

        // Perform the raycast
        if (Physics.Raycast(ray, out hit))
        {
            // Check if the raycast hits a UI element
            if (hit.collider != null && hit.collider.GetComponent<Button>() != null)
            {
                // Press the button if it's clicked
                ExecuteEvents.Execute(hit.collider.gameObject, new PointerEventData(EventSystem.current), ExecuteEvents.pointerClickHandler);
            }
        }
    }

    // Check if Left Shift key is held down
    if (Input.GetKey(KeyCode.LeftShift))
    {
        // Activate the toggle
        toggleActive.isOn = true;
    }
    else
    {
        // Deactivate the toggle
        toggleActive.isOn = false;
    }
}

}

wintry quarry
eternal falconBOT
edgy prism
rich adder
low robin
edgy prism
wintry quarry
#

Call that function from both the button and from your other code.

low robin
#

i have this many buttons.

wintry quarry
#

Thanks for telling me how many buttons you have.

low robin
#

yeah, because its impossible bruh.

wintry quarry
#

What's impossible?

low robin
#

adding the funtion like you said

wintry quarry
#

it is not impossible by any means

low robin
#

oh

wintry quarry
#

and you haven't explained under what circumstances you wish to call your function

low robin
#

because i am using XR input module for VR UI support but it doesent work in PC.

#

i have PC support because i get tired of putting on the vr headset and taking it off so mutch

wintry quarry
#

but what's the question? You're trying to just support the buttons on PC?

low robin
#

yea

wintry quarry
#

So why are you doing physics raycasts? What's wrong with the normal input module and event system stuff?

low robin
#

because vr is alreaddy there

wintry quarry
#

You can add both

low robin
#

oh

#

i dumb

wintry quarry
#

physics raycasts are never going to work for UI though

queen adder
#

I wanted to ask if i am making a pathfinding enemy for a procedurally generated maze and I want to use A Star algorithm for the path finding whats the best way of doing this?

wintry quarry
weak zinc
#

i need to change values of MapGenerator, but since i added this line of code it just shows this GENERATE BUTTON line" [CustomEditor(typeof (MapGenerator))]"

wintry quarry
#

Write the algorithm and use it

weak zinc
#

is it something in setting?

wintry quarry
queen adder
pallid nymph
weak zinc
wintry quarry
low robin
pallid nymph
low robin
#

i don't know

weak zinc
#

but this is what he ses

#

idk if its cuz its old video or cuz something is off in my settings

wintry quarry
weak zinc
#

sorry

#

thanks

delicate portal
#

Hey, the error is Only server can spawn NetworkObjects

low robin
#

um you have to be the server host i think

delicate portal
#

Well okay, but how do I spawn a player from clicking a button?

swift crag
#

You're just calling SpawnPlayerObjectServerRpc

low robin
swift crag
#

if you're a client, you run the method

#

ah, no, I am incorrect: it should execute that on the server if it has the ServerRpc attribute

#

but since it calls SpawnPlayerObjectClientRpc, that's sending an RPC to...everyone

#

and they all then try to run SpawnPlayerObjectClientRpc

delicate portal
#

Yes but if they only run on the server the client doesnt get recognized

#

Its just a prefab

#

As host

wintry quarry
# low robin thanks unity

do you have a graphic raycaster on the canvas? Do you have some other UI element blocking everything?

low robin
#

yes

dusk minnow
#

I have a Problem with collision detection, i want something to happen when colliding, but when my game Object(cube 3d) collides with a platform (long cube 3d) only on an edge, it doesnt detect a colission,why?

wintry quarry
low robin
#

you can turn off use gravity

dusk minnow
#

private void OnCollisionEnter(Collision collision)

low robin
#

make shure both the objects has isTrigger off.

wintry quarry
low robin
#

if you want trigger turn trigger on on them and use OnTriggerEnter

dusk minnow
wintry quarry
#

because right now there's if statements etc

low robin
#

yea start debugging it

dusk minnow
wintry quarry
#

Debug.Log will save your life kid

low robin
vapid void
#

horizontal = LeftAction.ReadValue<Vector2>(1.0f, 0.0f); there is an error at ReadValue where it says that read value cannot take two inputs, how do I make it so that the parenthesis attatch to the vector2?

wintry quarry
#

Readvalue doesn't take any parameters

#

how do I make it so that the parenthesis attatch to the vector2
This doesn't make sense

dusk minnow
wintry quarry
#

an if statement

#

your code is inside control things like that

#

add Debug.Log to your code to see which code is running and when

dusk minnow
#

yes ok imma log it

wintry quarry
#

and to print out values

dusk minnow
#

what values? like collided

wintry quarry
#

like the name of the object you collided with

dusk minnow
#

alr

meager raptor
#

does anyone know why there's a swiggly red under takedamage and attack?

swift crag
#

read the error message

meager raptor
swift crag
#

you have a second error on baseStats.attack

#

this is probably messing up the method invocation

polar acorn
lost anvil
#

with this tween sequence i have setup the nail goes back into the wall no matter if i make the value for moving it a negative or positive number idk why

https://gdl.space/itutobebac.cpp

meager raptor
polar acorn
#

they're quite relevant

tame mist
#

So I'm using a CinemachineVirtualCamera with the AIM setting to POV. now i see that when you use a freelookcamera there are properties you can access to disable and enable users mouse input to rotate the camera, for example -
public CinemachineFreeLook cameraLook;
cameraLook.m_YAxis.m_InputAxisName = "Mouse Y";
cameraLook.m_XAxis.m_InputAxisName = "Mouse X";

i see the properties in the CinemachineVirtualCamera script for the X and Y input axis names but i can't seem to figure out how to access them through code.
anybody know how to access those properties?

short hazel
#

<@&502884371011731486> Scam link

short hazel
tame mist
lost anvil
slender nymph
#

why do you have so many static variables?

#

also ScrewInteract.nail has absolutely no relation to HammerInteract.nail

sharp jay
#

static blushie

lost anvil
slender nymph
#

you're also starting so many DOLocalMoves since you start one per frame once that static bool is true

summer stump
#

I don't see a reason for ANY of those to be static

slender nymph
buoyant knot
lost anvil
#

so you cant interact with the nail after you already interacted and stuff like that

#

guess i could just disable the script on it for that

buoyant knot
#

what does that have to do with a variable being static

summer stump
lost anvil
#

yeah i dont know mate i was just using this to try and learn about sharing variables

slender nymph
#

i have a sneaking suspicion that they think making a variable static makes it have anything to do with some other variable of the same name and type on a different object that is also static (which of course it does not)

eternal needle
#

this is some cursed code. also it doesnt even look like these scripts are related or do anything to each other

buoyant knot
#

static means something is tied to the definition of the class, and not to an instance

slender nymph
buoyant knot
#

learn fundamentals before you try fixing something

#

you cannot fix what you do not understand

lost anvil
#

this is why i was trying to make this so i can understand

eternal needle
#

there is a LOT to fix, your best solution is honestly learning the basics first and then coming back to remake these scripts. this current way of coding is not fixable

lost anvil
#

ok

buoyant knot
#

yeah, we’d just be teaching you the basics of the language, which you can learn from many different tutorials

lost anvil
#

i know most of the basics just this is confusing to me

slender nymph
buoyant knot
#

static variables are a part of the basics

summer stump
lost anvil
summer stump
buoyant knot
#

references are core to C#. this is something you need to know very well

lost anvil
#

ok sound

eternal needle
# lost anvil i know most of the basics just this is confusing to me

just as a summary for things to learn more about,
as others pointed out, the static variables are a problem. learn to get a reference to an exact object that you want. the link posted to you by others is a good resource
the scripts seemingly arent related (not sure if thats intentional) but i cant see where you even call half these methods.
comparing the name of an object is pretty bad/fragile obj.name == "Item_Hammer" . someone accidentally naming something the same name or accidentally changing the name of this object will break your game.
in the HammerInteract script, you are calling Animate every frame if nailInteracted is true. this looks like something you would only want to do once, when you set the value of nailInteracted.

native seal
#

Is there anyway to make my pixel perfect camera use less pixels to handle rotations? idk exactly how to explain it but i want the arrow to be more jagged

low robin
#

i don't think there is a way

#

at least without modifying the image

native seal
#

it has nothing to do with the image as it is 16x16

low robin
#

oof

native seal
#

its how the camera handles it

low robin
#

i dont think there is a way then

native seal
#

ive seen a lot of games do it

timber tide
#

secondary camera without pixel perfect?

native seal
#

wdym

summer stump
native seal
#

it doesn't work

#

nvm figured it out, use "upscale render texture"

sour fulcrum
#

Think im goofing with dicts, any reason why this wouldn't be setting the value in the dictionary? (this code is running and the value is int)
currentRound.activePlayersDictionary[winningPlayer] = currentRound.activePlayersDictionary[winningPlayer] + 1;

polar acorn
#

Have you tried logging the value after setting it to make sure the code is actually running

quasi rose
#

Is there a way to do?

    public float DashCoolDown => _dashCooldown;
    private readonly WaitForSeconds _dashCooldown = new(3f);
#

obvious type mismatch here, but there's no like .Seconds or anything.

#

only thing i could think of is a create another variable for the time as a const float, and pass that in to both.

#
    public float DashCoolDown => time;
    private const float time = 2f;
    private readonly WaitForSeconds _dashCooldown = new(time);

meh guess so.

eternal needle
quasi rose
#

yeah but i want to access DashCoolDown elsewhere, but based on the _dashCoolDown time.

#

Which boils down to:

    public float DashCoolDown { get; private set; }
    private const float _dashCoolDownSeconds = 2f;
    private readonly WaitForSeconds _dashCooldown = new(_dashCoolDownSeconds);
#

But lmk if you're seeing something I'm not 🤔

slender nymph
#

if DashCoolDown is only meant to expose _dashCoolDownSeconds, why not just make the latter public? it's const so it's not like something else can change it

eternal needle
#

its more like you want to access DashCoolDown and have _dashCooldown be based on the time

quasi rose
quasi rose
slender nymph
#

it's not an instance member, treat it like static

quasi rose
#

Ah gotcha

#

Thank you.

hushed hare
#

Guys what is Good tutorial on unity? And should I learn Roblox Lua first I'm split between Roblox or unity

swift crag
#

!learn

eternal falconBOT
#

:teacher: Unity Learn ↗

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

abstract finch
#

For status effects do you create a class for each one combined with the usage of an interface or do you go with scriptable objects?

night mural
#

an SO for each effect which implements OnApply, OnTick handlers is a totally valid approach

#

for something as generic as statuses though it can be nice to have them be more like simple tags and handle the effects where they happen, depending on what kind of game you're making and how consistent your statuses will be

shell sorrel
#

to me would depend if its more logic or more data driven

#

if more data, and just a bunch of numbers defined for each effect, or each category of effect SO's can be nice for saving those numbers

#

if they are all very different and require different logic, a interface to apply them and a new class that implements it for each one

night mural
#

yep, i generally avoid that SO approach because 'statuses' tend to be a generic enough concept that it might do all sorts of stuff from preventing actions to preventing death to granting an ability and coming up with a consistent api for all that isn't worth the trouble

shell sorrel
#

yeah why i mentoned SO's for data driven or just a interface otherwise

#

Apply could take in a instance of the player and mutate it as it sees fit

night mural
#

definitly one of those systems where there's a few valid ways to go with pros and cons and what works for you really depends on what you're trying to do

swift crag
#

I've liked using SerializeReference to define effects

#
public class StatusEffectDefinition : ScriptableObject {
  [SerializeField] LocalizedString label;
  [SerializeField, SerializeReference] List<Effect> effects;
}
#

where Effect is an abstract class

#

with methods like Apply(Entity target)

night mural
#

is serializereference good? i used odin from before it existed and haven't tried to switch over cause i don't know if there's any weird gotchas

north kiln
#

The [SerializeField, is redundant

shell sorrel
night mural
#

i know, but before you could do it i used odin to accomplish what it does and so i still do that

#

but maybe i don't need to!

shell sorrel
#

its just a way to reference plain old C# classes that are serializable

#

instead of the normal SerilaizeField where its a copy of the data

north kiln
#

SerializeReference has no inspector for null values and that is one of the reasons why it's annoying

night mural
shell sorrel
#

yeah generally needs custom ui

#

cant really have a inspector for null, since it does not know what shape the data is

north kiln
#

And making a generic inspector that also supports property drawers and doesn't override the default editor is a pain in the ass, but I have a drawer that does it

shell sorrel
#

since it accepts interface types as well as concret types

north kiln
#

well, you can just have a selector of those subtypes, or a specified section of those subtypes

shell sorrel
#

somewhat easy if its a list thing

#

will just make the add make the correct data

north kiln
shell sorrel
#

i do find SerializeReference to be ultra fragile though

#

few months ago had what should be a perfect usecase but it was too fragile to long term use

#

no guid for the type, so a refactor can break all the references

night mural
#

yeah i am very way of any of my game data being in a state where it will break if i rename a class or move a namespace

#

i've been traumatized and take that divide probably too seriously now

north kiln
#

You can refactor the type fine using UnityEngine.Scripting.APIUpdating.MovedFromAttribute

night mural
#

odin has the same issues though

#

yeah but you have to remember to do that beforehand!

shell sorrel
night mural
#

you can revert and then do it if you notice early enough

north kiln
#

And Find and Replace is pretty good for it

night mural
#

but i didn't notice the stuff that had broken until i'd already done a bunch of other stuff and it was pretty rough

north kiln
#

But yeah, it is more fragile than others

swift crag
#

i also explicitly reserialize everything after making such a change

pseudo frigate
#

i have a top down 2d tower defense game and when i create the level im using the following code to create the bounds for the camera

    public Vector3 maxTile;
    public void SetLimits()
    {
        Vector3 worldPoint = GameManager.Instance.mainCam.ViewportToWorldPoint(new Vector3(1, 0));
        xMax = maxTile.x - worldPoint.x;
        yMin = maxTile.y - worldPoint.y;
    }

and then this in update to clamp it

 transform.position = new Vector3(Mathf.Clamp(transform.position.x, 0, xMax),Mathf.Clamp(transform.position.y,yMin,0),-10);

this was working fine until i tried to introduce zooming in/out (changing the cameras orthographic size). i figure i need to recalculate the limits when i zoom in/out, but everything ive tried so far isnt working right, any suggestions? thank you

swift crag
#

i don't like having "old" serialized data lying around my project

night mural
swift crag
#

i might just find-replace it...

swift crag
# night mural huh what do you mean by that?
    [MenuItem("Pursuit/Reserialize Identifiables", priority = 10)]
    public static void ReserializeIdentifiables()
    {
        AssetDatabase.ForceReserializeAssets(AssetDatabase.FindAssets("t:Identifiable").Select(guid => AssetDatabase.GUIDToAssetPath(guid)));
    }
#

Unity doesn't proactively update your assets

#

it updates them whenever you make a change to them

north kiln
swift crag
#

I think it also just doesn't get rid of removed fields at all? not sure

north kiln
#

yeah they stick around

swift crag
#

yeah -- so I can then immediately get rid of the attributes

#

modify code, migrate data, done

#

It cuts down on version control churn, too

#

I hate when stuff just...changes

night mural
#

ok yeah i have run into that but didn't think to look for a fix, that's excellent

swift crag
#

reserializing EVERY asset does take a while lol

swift crag
#
    [MenuItem("Pursuit/Reserialize Entity Prefabs", priority = 10)]
    public static void ReserializeEntityPrefabs()
    {
        AssetDatabase.ForceReserializeAssets(AssetDatabase.FindAssets("t:Prefab", new string[] { "Assets/Entities/" }).Select(guid => AssetDatabase.GUIDToAssetPath(guid)));
    }

notably

#

I also have some editor scripts that validate categories of assets

#

it's nice to be able to automatically check if you forgot something

night mural
#

yeah those i do have these days, at build time and/or as part of custom editors

limber narwhal
#

in editor log, is the last build details at the bottom?

night mural
swift crag
#

If the log is way too long to deal with, just restart Unity so that it writes a new log

limber narwhal
#

mine is definitely too long lol i'll do that now ty

wicked stratus
#

I have a sprite sheet that has 300 sprites on it. (it's a map that is split into a grid.) If I split it and handle it via spriteatlas, can I access each sprite via an index? if not, what would be the easiest way to do this? I need to have each sprite assigned an index

#

can I do this via code as well

#

it seems i'd have to refer to my resources, but i've seen varying opinions as to whether that's a good idea or not

#

it just would be a pain in the bum to manually drag all 300 into a slot and potentially make a mistake esp if code can do that for me

#

oh, especially cause i need to do this for 3 or 4 separate sprites

timber tide
#

it's what they're for, but no one says you can't make multiple sheets

wicked stratus
#

would it be more efficient that way

#

i mean for the computer. or is the price about the same

#

i guess it doesn't matter much

night mural
#

i would go with whatever feels easiest to you for now

#

until you run into something objective you're trying to solve

hushed hare
#

Guys do you know any good torurials

#

For fps

tame mist
#

probably not the right place to put this but I don't see a channel for Unity Profiler questions.
anyways I was wondering if someone could help me read this profiler data, this is my first time using the Profiler.
it looks like a script is causing me a huge lag spike when it turns 9am in my game.
at 9am my TimeOfDayController script Invokes an even that several or more other scripts listen to. that 9am unity event also activates 3 pooled car objects and run one or two methods on one of their components.

I'll include the code I'm specifically profiling -

    {
        carsForPurchase.Clear();
        Profiler.BeginSample("For Loop Online Cars");
        for (int i = 0; i < 3; i++)
        {
            int randomInt = UnityEngine.Random.Range(0, carIndexesAvailable.Count);

            var spawnPoint = spawnLocations[i].transform;
            GameObject obj = cars[carIndexesAvailable[randomInt]];
            obj.transform.position = spawnPoint.position;

            obj.AddComponent<CarDriveForwardArcade>();
            obj.GetComponent<CarDriveForwardArcade>().arcadeVehicleController = obj.GetComponent<ArcadeVehicleController>();

            obj.SetActive(true);
            obj.GetComponent<CarStats>().RandomizeCarColor();
            obj.GetComponentInChildren<CarStats>().RandomizeCarResellPrice();

            handleActiveCars.AddCarToList(obj);

            //carsForPurchase.Add(obj);
            buyingCarsOnlineController.AddCarToCurrentCarsForSaleList(obj);
            carIndexesAvailable.Remove(randomInt);
        }
        Profiler.EndSample();
        ResetCarIndexList();
    } ```
woven crater
#

why does it stuck to the wall when i press move toward it?

frigid sequoia
woven crater
#

material?

summer stump
woven crater
#

okie thank

eternal needle
# tame mist

can you collapse some of those and see whats taking a majority of the 256 ms? in the current code, the only areas that could really take awhile is the method calls whos implementation which we cannot see

vale karma
#

this has been eating at me all day. I cant figure out what i did wrong in the tutorial. I get this error:
NullReferenceException: Object reference not set to an instance of an object
DisplayInventory.AddEvent (UnityEngine.GameObject obj, UnityEngine.EventSystems.EventTriggerType type, UnityEngine.Events.UnityAction`1[T0] action) (at Assets/Player/Inventory System/Inventory/Scripts/DisplayInventory.cs:83)

at this line of code: AddEvent(obj, EventTriggerType.PointerEnter, delegate { OnEnter(obj); });

gaunt ice
#
trigger.triggers.Add(eventTrigger);
wintry quarry
#

I.e. there's no event trigger component on the object

gaunt ice
#

three possibilities: trigger is null, triggers is null or both of them

vale karma
#

he wrote the reference thru code, but im not seeing it trying to catch glimpses

wintry quarry
#

And it seems like you probably don't

#

That's not a code thing

vale karma
wintry quarry
#

It's a "how you set up the prefab" thing

vale karma
#

I put the event trigger on the inventory background basically, shoudl i have put it on the button/slot itself?

wintry quarry
vale karma
wintry quarry
vale karma
#

its on the bottom right, im guessing i have it on the wrong object. I will try it on the prefab and get back toya

#

OMG i love all of you

#

come here

#

mwah

potent nymph
#

I'm trying to add an onclick listener to buttons that simply log out its index in the buttons array, but it's logging the length of the array instead. Here's the code:

    [SerializeField] private Button[] hairSelect; //8 buttons total

    private void Awake()
    {
        for (int i = 0; i < hairSelect.Length; i++)
        {
            hairSelect[i].onClick.AddListener(() => HairSelect(i));
        }
    }

    void HairSelect(int index)
    {
        Debug.Log(index); //logs 8. Expected 0, 1, 2, etc

    }
teal viper
potent nymph
#

@teal viper worked wonderfully, thanks!

tame mist
fiery badger
#

Hi guys, if i put a script in a Child gameobject and want to get components in Parent gameobject in Start(). How to do that?

north kiln
#

Why get them in Start, why not just assign them in the inspector?

fiery badger
#

Just wondering if its possible

north kiln
#

Sure, GetComponentInParent

fiery badger
#

Alright i will test it out thanks

teal viper
teal viper
crimson ibex
#

Hello. I am unable to find correct way to calculate "touch" position in 3D world. Here I have added 30f randomly to get it closer. camera.transform.position.y also does not get correct value. All youtube tutotials use input.mouseposition or are 2d games 😦

gaunt ice
#

screen point to ray
then raycast for 3d game

crimson ibex
#

ohhhh !! is that so ! thank you so much

solid sail
#

If II have a class A and B, Like this but this get an error public class A<T> : B<T, A<T>> I want to pass A<T> and T both to B how do I do it?

thin hollow
#

I have a question.
i am instantiating a game object with a script. that gameobject has a script component that takes in a variable called Character_Class, which is a scriptable object.
I have a scriptable object named "knight" in my Assets folder.

is there a way to create an instance of knight and add it to that new gameobject?
i Tried something like

Job job = newChar.GetComponent<Job>(); var cc = ScriptableObject.CreateInstance("Knight"); job.characterClass = (CharacterClass)cc;

crimson ibex
solid sail
#

I cant inherit 2 class the same time

#

if I use parent class to inheired singleton.It will create parent class instance.That's not what I want

#

Maybe there're some solution or some alternative?

teal viper
#

And I'm not sure if this kind of recursive generics are even allowed. I wouldn't mess with them too much.

gaunt ice
#
abstract class Singleton<T> where T:class{}
abstract class Middle_0<T>:Singleton<T> where T:class{}
class Leaf:Middle_0<some class>{}
```child class having all properties parent class has (an "instance" of parent class is created but stored inlinely), no idea what do you mean by "dont want parent class instance" but you want child class inherits parent, instance of child class can be treated as instance of parent class
#

if you mean by stopping others create an instance of that parent class, use abstract

solid sail
#
...
GoldenLeaf.Instance.func().....```
#

This will create Leaf instance instead golden leaf

#

I want to create goldenleaf instance

teal viper
#

GoldenLeaf is a class. "Create goldenleaf" doesn't make sense in this context.

#

Unless you mean an instance of GoldenLeaf

#

Oh, misreading the message again lol

#

This wouldn't create anything. It accesses the Instance and calls it's func

solid sail
#
       where T : MonoBehaviour
{
    private static bool applicationIsQuitting = false;
    private static T _instance;
    private static object _lockObj = new object();
    public static T Instance
    {
        get
        {
            if (applicationIsQuitting) { return _instance; }

            if (_instance != null)
            {
                return _instance;
            }

            if (_instance == null)
            {
                _instance = FindObjectOfType<T>();
            }
            if (_instance == null)
            {
                lock (_lockObj)
                {
                    GameObject go = new GameObject("[MonoSingleton]" + typeof(T).Name);
                    _instance = go.AddComponent<T>();
                    DontDestroyOnLoad(go);
                }
            }
            else
            {
                DontDestroyOnLoad(_instance.gameObject);
            }
            return _instance;
        }
    }```
#

Singleton class will create gameobject then attach component to it

teal viper
#

Okay, yeah, that would create and return a component of type T, so what's the problem?

gaunt ice
#

please replace the leaf to your actual implementation....
it is just a place holder.... (the leaf node in your inheritance tree....)

#
public class MyMonoSingleton<T> : MonoBehaviour
       where T : MonoBehaviour
```no need to constraint T as monobehaviour
#

everything inherits from this is monobehaviour

solid sail
#

I was intened to split the code into 2 class. Dont want them crowd in a single class tho

#

Abstract may be impossible

teal viper
#

You could use a partial class, but I feel like there's a bigger design problem due to you overcomplicating

solid sail
gaunt ice
#

if i have a class EnemyManager
which inherits from your singleton

class EnemyManager:MyMonoSingleton<EnemyManager>
```is it monobehaviour?
#

you didnt actually require T has any special properties (in this case you will need interface), you just need its type

solid sail
teal viper
solid sail
#

I have NetWorkClient inherited from NetWork. And NetWorkClient need to be create instance and show in the scene

teal viper
#

I still don't see how it's related to the question? I wouldn't have these classes as singletons in the first place. And even if I do, I'd either implement it as Tina suggested or avoid generics entirely and just implement the singleong logic within it.

solid sail
gaunt ice
#

mb, nvm
it should be abstract function not interface

public abstract class Root<T>{
  public abstract void MethodA(); 
}
public abstract class TreeNode:Root<int>{
  public override void MethodA(){
    the implementation;
  }
}
```if you need child class to have some methods
solid sail
ruby python
#

Mornin' all, having the weirdest issue and can't see what I'm doing wrong. IDE (VS) is all configured properly, but for some reason it's not 'picking up' Random.Range. I've used it so so many times before, but it's just stopped recognising 'Range' 😕

solid sail
#

I found a way.I can use type of the get the type of A<B> (B : A), and B is exactly I want

gaunt ice
ruby python
#

Usually I just use system

gaunt ice
ruby python
#

Weird. Genuinely never had that issue before, but using UnityEngine.Random fixed it.

lavish gate
#

Pretty sure that tells you exactly what the problem is

#

For this error

#

Error list is the name

tame mist
teal viper
tame mist
#

I shared the code earlier but I can post it again.
this is the "For Loop Online Cars" profile test I made for the following code -

    {
        carsForPurchase.Clear();
        Profiler.BeginSample("For Loop Online Cars");
        for (int i = 0; i < 3; i++)
        {
            int randomInt = UnityEngine.Random.Range(0, carIndexesAvailable.Count);

            var spawnPoint = spawnLocations[i].transform;
            GameObject obj = cars[carIndexesAvailable[randomInt]];
            obj.transform.position = spawnPoint.position;

            obj.AddComponent<CarDriveForwardArcade>();
            obj.GetComponent<CarDriveForwardArcade>().arcadeVehicleController = obj.GetComponent<ArcadeVehicleController>();

            obj.SetActive(true);
            obj.GetComponent<CarStats>().RandomizeCarColor();
            obj.GetComponentInChildren<CarStats>().RandomizeCarResellPrice();

            handleActiveCars.AddCarToList(obj);

            //carsForPurchase.Add(obj);
            buyingCarsOnlineController.AddCarToCurrentCarsForSaleList(obj);
            carIndexesAvailable.Remove(randomInt);
        }
        Profiler.EndSample();
        ResetCarIndexList();
    } ```
#

@teal viper ^

teal viper
gritty wagon
#

Hi guys, I am working on a little game, and I have made some animations for my character, however they are very delayed from when I press my input buttons, I can provide code and a video if needed.

My animation tree looks like the image, and I have removed exit time as I thought that might be the cause, but still nothing

tame mist
teal viper
gritty wagon
#

oh ok ill record the animator as well

tame mist
#

I understand this method does more than what it should and I plan on refactoring it soon, but for now i would like to explain that i'm using the ES3 Easy Save asset. and the reason i'm temporarily saving to a different file and reloading it is because cars seem to drift better after they have been saved and reloaded. It's hard to explain but the car controller I'm using, pretty sure it's Arcade Vehicle Physics, will save a bit different and a car instantiated or set active in the scene drives a bit differently than a car that has been loaded from ES3. I couldn't find what or why it would change the car handling but it would so to keep the handling consistent on the vehicle i will save and load first and get rid of the temp save data in the temp file. anyways, here's my code -

 public void RandomizeCarColor()
    {
        float randomNumber1 = Random.Range(10, 90);
        float randomNumber2 = Random.Range(10, 90);
        float randomNumber3 = Random.Range(10, 90);
        randomNumber1 = randomNumber1 / 100;
        randomNumber2 = randomNumber2 / 100;
        randomNumber3 = randomNumber3 / 100;
        spawnColor = new Color(randomNumber1, randomNumber2, randomNumber3, 1.0f);
        oldCarMaterial.SetColor("_Color", spawnColor);

        metallicValue = 0.35f;
        oldCarMaterial.SetFloat("_Metallic", metallicValue);

        ChangeMaterialsOfCar();

        carID = this.gameObject.GetInstanceID();

        ES3.Save(carID.ToString(), this.gameObject, "tempCarData.es3");

        this.gameObject.SetActive(false);

        GameObject obj = ES3.Load(carID.ToString(), "tempCarData.es3") as GameObject;
        obj.SetActive(true);

        if (ES3.FileExists("tempCarData.es3"))
        {
            foreach (string key in ES3.GetKeys("tempCarData.es3"))
            {
                if (key.Equals(carID.ToString()))
                {
                    ES3.DeleteKey(carID.ToString(), "tempCarData.es3");
                }
            }
        }
    } ```
teal viper
eternal falconBOT
gritty wagon
#

It looks like it can't exit an animation early

#

is there something I need to turn off or on?

tame mist
gritty wagon
#

With the jumping animation, if I only jump low, it doesn't have time to finish the jumping animation before falling and instead just plays the jump animation on the way down as well

teal viper
teal viper
gritty wagon
#

oh might be the setting of fixed duration

#

let me just try

teal viper
#

Yeah, fixed duration would make the transition last a fixed duration

gritty wagon
#

okay the jumping is much better now

#

but the running is still weird

#

i think it might be because i check the velocity of the rigid body, I should probably check for user input

#

is GetAxisRaw just returning 0 or 1?

#

nvm -1 to 1

teal viper
gritty wagon
#

aight ty

#

ig just checking if its zero or not will be what determines if i run

gritty wagon
# teal viper Yes.

Is there a way to stop animations from fully finishing before transitioning?

Almost everything works now, but if I stop running, it finishes the running anim fully before switching to idle, which causes the player to keep running in place for half a second, looks kinda odd

#

I can do another vid

teal viper
gritty wagon
#

is it the exit time?

#

but i can't turn it off without any conditions

teal viper
#

Mmmm... I think it's the "Has Exit Time" checkbox

gritty wagon
#

But I can't turn that off as long as it doesn't have any conditions

teal viper
#

Yeah, you'll need some kind of condition. Otherwise, it would transition to it all the time.

gritty wagon
#

Should I just put the conditions that nothing else is on?

teal viper
#

Yes

gritty wagon
#

nvm i cant

#

with triggers

#

there is no on/off

teal viper
#

Ah, well, then you'll need to think about your setup overall.

#

In the first place triggers don't make sense for stuff like running, as it's a continuous state

gritty wagon
#

hm, i tried just using my booleans and if they were false, but that doesn't work at all lol, then it just spams idle

#

I know, I don't use it for running

#

I have it for Jump, Attack, TakeHit and Death only

teal viper
#

Then you'd probably need transitions from each state to idle

#

For example, Attack shouldn't transition to idle immediately, but Run should

#

You can't use one transition from every state as they all have different requirements.

gritty wagon
#

Oh okay

#

Can I setup different conditions with the "Any State", or do I have to do transitions between them?

teal viper
gritty wagon
#

Okay, I'll do that, thanks 😄

tame mist
lilac hemlock
#

normalised time is correct. I think the issue is in curveDisplacement or the way the math works. However, i am not very good at 3d space math.

icy grotto
#

hi, is there a way to print two elements without using for loop?

hexed terrace
icy grotto
tender stag
#

what is the most optimal way of saving inventory

#

as a json file or player prefs

timber tide
#

player prefs no

tender stag
#

why not?

timber tide
#

persistency problems compared to just using json

tender stag
#

alright thanks

timber tide
#

also limited serialization, even though json utility isn't that much better

#

grab the newtonsoft package

swift crag
#

One: How do you turn the inventory into data?
Two: How do you store that data?

#

PlayerPrefs and a JSON file are how you store serialized data

#

But you still need a way to actually do the serialization

#

JsonUtility can perform serialization, as can Json.NET (and the latter can handle much more complex data)