#archived-code-general

1 messages · Page 306 of 1

toxic prawn
#

im trying to make a game that bteaks the 4th wall a lot and thid seemed a good way to do it snd help me with future 4th wall breakings

soft shard
toxic prawn
#

yes

#

I want to mess with other apps like google diacord etc.

lean sail
#

Yea thats not gonna happen

#

at that point, you have basically created a virus

toxic prawn
#

for it to be a virus it needs to send data to the developers or cause damage to the sevice

#

but the ide is similar yea

lean sail
#

i use the word virus here very vaguely, theres nothing to distinguish between a program who wants to mess with someones other apps compared to a malicious attack

#

Anyways you should describe what you're trying to do, "mess with other apps" could mean a lot. There really isnt much you can do from outside besides like kill the process, in which case users will instantly refund your game

soft shard
#

Assuming the game gets approved for uploading, something like that would likely be detected by whoever reviews your game on the platform you upload, and could violate developer contracts for that platform (but that gets legal, which is a whole other thing)

toxic prawn
#

i dont think ill share it publicly

lean sail
#

still, theres nothing you can really do. You cannot just connect to someones chrome or discord and do anything

toxic prawn
#

how does this work?

soft shard
toxic prawn
#

¯_(ツ)_/¯

toxic prawn
cosmic rain
#

Though, the best you can do to get any data back is wait for it's closing code. Unless it's an app that you wrote yourself. Then you might be able to establish some kind of interprocess communication.

toxic prawn
cosmic rain
toxic prawn
swift falcon
#

Maybe need a namespace

cosmic rain
#

Do you have IDE configured correctly? It should suggest you the correct namespace...

swift falcon
#

VS automatically puts the namespace there for me

cloud python
rigid island
#

how could we possibly know without seeing the death script

cloud python
#

they all worked before

rigid island
#

that takedamage method 😵‍💫

rigid island
cloud python
#

this

cloud python
cloud python
rigid island
cloud python
spring creek
rigid island
spring creek
rigid island
#

this code is honestly a chore to glance over, so much repetition

#

huh ? why is it in the checkpoint script?

cloud python
rigid island
#

yeah but you have checkpoint code inside a OnState exit of animator? seems weird to rely on animator at all for that

cloud python
rigid island
spring creek
# cloud python unity

Are you saying you are using Unity Version Control? Then how did you accidentally delete the animations? Just don't commit that change

cloud python
spring creek
cloud python
cloud python
spring creek
toxic prawn
#

how do I get the folder path of assets?

sturdy haven
#

I was thinking of using Unity for a 3D human pose estimation system, to visual a squash game in a 3D interactive environment, has anyone ever done anything similar for a different sporting game, also could I embed my program or the results of my program into a web application? I've never used unity before but am a confident programmer.

cloud python
spring creek
cloud python
rigid island
cloud python
dim canopy
#

is there any easy free solution to implement text to speech on windows, ive tried using LMNT and using MRTK, MRTK straight up didnt work and LMNT was very buggy and pretty well broken

smoky crow
#

could I get some help with this?

UnityAction nextEvent;
void SkipLine(DialogueLine line)
{
  //do stuff
}

void Start()
{
  nextEvent += () => SkipLine(line);
}

output:
Object of type UnityEngine.Object cannot be converted into DialogueLine

I've tried adding that lambda directly to an event as a listener, tried adding another event inside the script, and adding it to that, then adding the event to the event I'm trying to listen to etc. I'm lost at this point

#

the error points to UnityEvents.cs

#

DialogueLine is a ScriptableObject too

cosmic rain
inner yarrow
#

Is there a good way to find the object that is closest to a point? Visualize it like making a sphere at a point that expands until it hits an object.

#

I could make my own crude implementation, but I was wondering if there's a built in way of doing this.

cosmic rain
#

An overlap sphere and then sort/search for the closest object

smoky crow
wheat spade
#

I've been hitting my head about this problem for the past few hours. Can anyone offer advice? I have a Dictionary<Vector3, Vector3>, and calling ContainsKey() acts oddly sometimes. Using breakpoints, I can verify the Vector3 is in the dictionary, but ContainsKey() returns false.

cosmic rain
full canopy
#

Hey yall, im having some problems with rigidbody.addexplosionforce
I'm making a grenade in vr meant for launching yourself. it works just fine on every other object in the scene, but not the player. What's weird is I have scripts on the player that allow jumping or moving by adding force and work just fine, but force cannot be added via the grenade.
I also tried making my own add explosion force with just a more complicated addforce function but to no avail. I've also tried switching forcemode to velocity change and still no effect.
The rigidbody is not kinematic at any time, and yes I have tried increasing the grenade's force significantly, as in like 10000000. the radius is also just fine, it's moving objects farther away than the player

knotty sun
full canopy
#

i tried disabling every script exept the ones strictly necessary (like moving the hands and head for vr) on the player controller and still nothing happened so i will try to pass it to a new script on the player and see what happens

wheat spade
# cosmic rain Floating point comparison is very unreliable. You shouldn't use a Vector3(that i...

When I was building the implementation of the Dictionary, I wondered if that was a problem. I read that the unity Vector3 struct overloads the == operator to check the squared magnatude of the distance between the Vectors, instead of checking xyz cordinates for exact equality. Decompiling the Vector3 struct revealed the margin of error to be 9.99999944E-11f. So yes, I'm going to have to make my own Vector3 implementation. : (

cosmic rain
lean sail
knotty sun
full canopy
#

i made my own script attached to the player and it still wasnt working which was very confusing

#

it just hit me that the player rigidbody never existed in the list of rigidbodies in the radius

#

because i totally forgot that the exploding object's layer does not have collision with the player as i dont want items getting pushed away while youre trying to pick them up

knotty sun
swift falcon
#

this is my image, which contains the following children. How do I, in the script, make Player(1) and it's children not be rendered?

I have tried set active, get component and a few other fixes, furthermore when I toggle the eye icon in hierarchy view in editor, the image has it's rendered turned off only in editor, not in game view? Please help.

prime sinew
#

what are you doing?

#

all you need to do is just get a reference to Player(1) and set it to inactive using SetActive

quartz folio
#

toggle the eye icon in hierarchy view in editor, the image has it's rendered turned off only in editor, not in game view
That's what it does, yes

prime sinew
swift falcon
#

let me try again

#

nvm turns out i made a stupid mistake

#

thankyou though

dawn nebula
#

So I'm sort of a fan of read only data objects. If I want to make these properties visible in the inspector, is this really what I need to do?

knotty sun
dawn nebula
#

Honestly even after all these years I'm still not exactly sure of the interaction between constructors and objects unity serializes.

knotty sun
#

almost all serializing systems use Activator.CreateInstance to make an instance of a given class, this requires the class to have a parameterless constructor.
Now any class which does not define a constructor will have that by default however as you have declared a parametred constructor you also need to declare a parameterless one yourself

dawn nebula
knotty sun
#

serializing/deserializing will not work

dawn nebula
#

Will not work as in nothing will show, will not work as in stuff wont get saved, or will not work as in stuff gets... freaky?

knotty sun
#

there is a fallback, Formatter.CreateUninitializedInstance but I doubt Unity uses that.
will not work as in will throw an exception of just will not do anything depending on how it is implemented

knotty sun
#

does it actually save anything if you make changes?

dawn nebula
#

changes I make stay into play mode

#

and out

knotty sun
#

which is internal not seriaized

dawn nebula
#

Well changes I make to the values in the inspector are maintained.

#

Closing Unity and reopening also maintains it.

knotty sun
#

ok, so they are using Formatter not Activator

dawn nebula
#

I think the wildest thing I've done is I had a serialized class that took in a Func, which I defined in variable initialization.

#

And it worked.

#

Like this works.

quartz folio
#

It has nothing to do with serialization, so sure

#

Every variable initializer will be called as usual; and if the field is serialized the serializer may come along afterwards and replace the value that was there

dawn nebula
#

Is there a channel for code review?

knotty sun
#

@dawn nebula As I suspected they are Using Formatter which does not require a constructor. So..

public class NewBehaviourScript : MonoBehaviour
{
    public Test test;

    // Start is called before the first frame update
    void Start()
    {
        test.Print();
    }
}

[System.Serializable]
public class Test 
{
    public int x;
    int y = 2;

    public Test(int z)
    {
        x = z;
    }

    public void Print()
    {
        Debug.Log($" {x} {y}");
    }
}

outputs

#

but if I add the paramaterless constructor to Test the output is

dawn nebula
#

So y isn't getting initialized properly?

knotty sun
#

exactly, because y is initialized when the constructor is called

dawn nebula
#

how does X even get a value of 1?

knotty sun
#

I set it in the inspector

dawn nebula
#

kk

#

Well that's annoying but not... horrific I guess.

knotty sun
#

rule of thumb, if you ever add a parameter constructor to a serialized class always add a paramaterless one as well

dawn nebula
#

In general or just with Unity?

knotty sun
#

in general

dawn nebula
#

Why?

knotty sun
#

because most systems will not use the Formatter fallback and so will throw an exception

dawn nebula
#

Damn. I like the guard rails made by constructors.

#

Anyway, can I toss a short script (~70 lines) in here for review?

gray mural
dawn nebula
gray mural
tawny elkBOT
dawn nebula
#

This is a generic timer class that I use.

#

I just subscribe what I want to happen to the OnDone callback.

#

and tick the timer in Update

knotty sun
#

this
Target = Mathf.Clamp(newTarget, 0, Mathf.Infinity);
is a very bad way to say >= 0f;
also I would check if newTarget != Target
not too sure about your variable names either

#

also this
public bool IsDone => Current == Target;
is very dodgy

dawn nebula
lean sail
#

I would be surprised if you ever actually use any of those first 3 events too

knotty sun
#

yes it can if Target is not directly divisable by all the accumulated deltas

lean sail
#

this seems like something you create for the purpose of a small use case, not something thats passed around to be used by many scripts

dawn nebula
#

Like for example a UI timer.

knotty sun
#

tbh it looks like a sledgehammer to crack a nut

dawn nebula
#

LOL

lean sail
#

i could definitely see some use out of a basic timer because i do find myself doing the classic
time += ...
if time >= something, time -= something.
But yea this is overkill

dawn nebula
knotty sun
dawn nebula
#

I guess that's fair, but current will not (or shouldn't >_>) ever exceed target.

knotty sun
#

if you use Time.deltaTime as your delta you can guarantee it will be

dawn nebula
#

after the clamp

lean sail
#

i dont think it really matters if it does in your case. You could just have the property for current return target if its larger. Clamping between all this isnt needed

knotty sun
#

if you take the clamp away. why clamp something that doesn't need to be clamped.
this is a typical example of a CS Student implementation of a simple problem

dawn nebula
#

😔

#

That one hurt the ego a bit.

knotty sun
#

it's just a question of experience, no offence intended

lean sail
#

It would be a lot simpler if this class was something that could exist on it's own, without needing to call Tick().
But then you would be somewhat recreating a small portion of what tweening libraries do

#

Right now, this code doesnt really make anything easier for other code

dawn nebula
dawn nebula
#

If I wanted something running by itself I could do something wild like a pool of gameobjects that hold timers.

knotty sun
dawn nebula
knotty sun
dawn nebula
#

I was recently involved in a game jam, and I'm going through some of the general utility scripts I wrote and cleaning them up for future use.

#

This timer was one of them, and I found the pattern of just subscribing to the OnDone event and calling Tick to be pretty clean.

mossy snow
#

it's the opposite of clean in my eyes. Why did you make it a poco class? The problems I have with its design all stem from that

knotty sun
dawn nebula
mossy snow
#

You have a weird half-serialized mutt class that can only be used if it's tightly coupled to whatever thing uses it. What is your justification for making it a plain class instead of a MonoBehaviour? It's built in a super weird way

dawn nebula
#

Plus the game I was working on needed controlled pausing. The timer had a Tick method that took in a delta. It seemed weird to extend off a class that has Update.

#

If I wanted a Unity implementation I could always wrap it in a Monobehaviour and hook up some UnityEvent callbacks to it 🤷‍♂️

mossy snow
#

hmmm yagni is your friend in a situation like this

dawn nebula
#

By the end of the Jam I was setting up timers like this.

#

Running them like this.

#

And setting them up in the inspector like this.

mossy snow
#

where half of the timer is set up in the inspector, and the other half in code? That's one of the reasons I don't like your setup. Look at the snippets you posted. You apparently have a timer script, except it's three sub-timers and a GameManager in a trench coat with its fingers in day/night, generating "offers" and has something to do with the economy

#

and you got forced to mash it all into one place because you made your timers plain classes so the design is awkward

dawn nebula
#

I've done freakier things.

honest trout
#

can anyone help me with this error message?

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class NewBehaviourScript : MonoBehaviour
{
    private PlayerInput playerInput;
    private PlayerInput.OnFootActions onFoot;

    private PlayerMotor motor;

    // Start is called before the first frame update
    void Awake()
    {
        playerInput = new PlayerInput();
        onFoot = playerInput.onFoot;
        motor = GetComponent<PlayerMotor>();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        motor.ProcessMove(onFoot.Movement.ReadValue<Vector2>());
    }
    private void OnEnable()
    {
        onFoot.Enable();
    }
    private void OnDisable()
    {
        onFoot.Disable();
    }

}```

heres the code
knotty sun
dawn nebula
knotty sun
dawn nebula
#

Dont worry about that part.

knotty sun
#

I worry about everything, it's in my nature

gray mural
knotty sun
#

without context of the use case it's difficult to say if this is sensible or not but I see a lot of garbage being generated there which I do not like

gray mural
#

You can unsubscribe none of them

dawn nebula
gray mural
#

If you don't want to unsubscribe them, consider using events in order to add non-permanent listeners

myClass.myEvent.AddListener(() => ...);
lean sail
#

If you hover over the => it should tell you what is being captured in all those

#

Or maybe I am thinking of the wrong place to hover, but something in there should tell you

dawn nebula
knotty sun
light pond
#

please help me with this problem i havent gotten a working answer half of this week

dawn nebula
#

I just... didn't make them structs 🙃

knotty sun
thin aurora
#

This video explains nothing but a possible issue with rendering

dawn nebula
inner mist
#

Does it make an big diffrence if i use the normal 3d and the tutorial is made in URP?

knotty sun
inner mist
#

Okay

inner mist
knotty sun
dawn nebula
lean sail
knotty sun
knotty sun
dawn nebula
#

So realistically those event objects are being generated 0 times per frame until one of those things go off. In which case it's probably around 2-4 events per action.

knotty sun
gray mural
light pond
#

as you can see the tile doesnt swap when i jump

#

but the boxcollider does enable and disable

#

so i think this is an issue in the rendering

dawn nebula
dawn nebula
light pond
#

how can i fix this problem

crude mortar
light pond
#

its the wrong video

#

XD

smoky crow
#

Unity hub isn't installing the windows build tool for some reason on my machine

Could someone zip and send the WindowsPlaybackEngine for unity 2022.3.22f1 to me?

you can find it at Unity Hub/Editors/2022.3.22f1/Editor/Data/PlaybackEngines/WindowsStandaloneSupport/

Either that or tell me where I can find a download for it online

light pond
light pond
crude mortar
# light pond here is the real video

when you build your game, if you enable the "Development Build" checkbox, you will be able to see errors show up in a console window on the game. So, maybe do a development build to make sure you aren't getting any errors.

light pond
#

do i need any of these

crude mortar
#

no

#

If nothing shows up, then there aren't any errors

light pond
#

there arent any errors except a different one because its trying to load the next scene which doesnt exist

crude mortar
#

Seems like a weird issue with SwapTile, try calling redMap.RefreshAllTiles() and blueMap.RefreshAllTiles() at the bottom of your FlipTiles method

#

Not really sure why it would be messing up in the build though

rapid stump
#

I'm trying to make a minimap sort of thing using an orthographic camera, and just 15 minutes ago it was working. But now... I'm running into an error I don't understand XD
In the video you can see that I have an orthographic camera that in attached to a render texture, which is then fed into a raw image in my UI, as the minimap display.
But when I run my game, I get hit with a lot of debug logs saying that my camera isn't assigned, although... you've seen it is. And the WEIRDES part, is that I can STILL move the camera by dragging on the minimap display, meaning that it IS assigned. So when I'm not touching the minimap display, why is the camera "not assigned" in the eyes of the script?

crude mortar
#

Try putting Debug.Log($"Running from {gameObject.name}!", gameObject); in Start of your script

smoky crow
rapid stump
#

If you mean the one I closed, no that was from my test project where I first implemented the minimap.
And I used the debug log you sent, it just says "Running from MiniMapController" which is just the name of the script. I looked for any other objects that have that script attached, and there's only one. So idk anymore XD

#

It's just so weird because I have it check if the camera is null. If it's not, then say "MinimapController: Update: Entering HandleZoomInput!", which when I interact with the UI image that has the images created by the minimap camera, it sends those debug log. And as soon as I stop interacting with it, it goes back to saying it's null

#

And it's so annoying XD

crude mortar
#

The log I recommended should have printed the name of the gameObject that the script is on, not the name of the script. And the point of the log is to see if it logs more than once. You could enable Collapse mode in the console to make it easier to see. If you do that, and it does really only log once, then I would be suspicious of the fact that your miniMapCamera variable is public, meaning that any other script in your entire project could modify it.

rapid stump
#

WAIT

rapid stump
#

I just noticed. There ARE two debug logs. But... how? The first one is the object I attached the script to. The second one is the literal script...
And no other scripts are modifying this one because I just implemented it

#

I haven't had the chance to do anything else

crude mortar
#

Why don't you scroll all the way down in the list of components on both objects?

rapid stump
#

Already found the issue

crude mortar
#

If it isn't there when the game is not running, then it must be getting added at runtime

rapid stump
#
    private static MiniMapController _instance;
    public static MiniMapController instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = FindObjectOfType<MiniMapController>();
                if (_instance == null)
                {
                    GameObject go = new GameObject("MiniMapController");
                    _instance = go.AddComponent<MiniMapController>();
                }
            }
            return _instance;
        }
    }

This.
I guess I have to find a new way to access variables in a seperate script.
Any ideas? XD

#

Also thank you so much

#

That part of the script was the reason it was running twice

crude mortar
#

Maybe you could explain where that code you just sent is (which file it's in), and what other code uses the instance variable

#

but, generally speaking, I just wouldn't recommend creating a new gameobject and adding a component there. You need to assign variables in your script anyways, so it would be uninitialized if you just AddComponent and do nothing else with it.

#

I would instead just ensure that it's in the scene. If it's not, I would throw an exception or log a warning so that you know you have made a mistake by forgetting to add it to the scene

crude mortar
rapid stump
#

Oh sorry
That code snippet is just below my variables
https://pastebin.com/ribWvX3Y

And the reason it's running twice is because it's attached to a gameObject and already instanced. And then that code snippet is then creating a second instance which was running all the errors.
Now if I remove that snippet the problem goes away, but I can't reference any variables in this script in any other scripts.
I tried attaching the script to an empty objects, like most of my other event scripts, but I can't figure out how to handle onDrag events, etc when it's not attached to the object with the events itself

crude mortar
#

If it's already instanced, wouldn't your FindObjectOfType call assign _instance and therefore not run the second part of the snippet?

rapid stump
#

No it still runs the snippet because they're different names. The first instance that is created is the name of the object the script is attached to, "NewMap". The second instance it's creating is "MiniMapController" Which doesn't exist yet, so, it creates it

crude mortar
#

FindObjectOfType finds the component type, not the gameobject name

rapid stump
#

I think I'm just going to attach the script to an instance of an empty object, like my other event handlers, and make the image it was previously attached to just send events with "Even Trigger"

rapid stump
#

But it is

crude mortar
#

Well, me neither.. it shouldn't be, so all I can do is guess that you are trying to access the instance variable from another scene, before the scene with your "NewMap" object is loaded. But I don't know anything else about your project, so not sure if that could be an issue or not (from the looks of your video, it isn't the issue)

versed spade
#
    public void GenerateCustomizationOptions(ShipData shipData, List<WeaponObject> weaponObjects, List<ComponentObject> componentObjects)
    {
        Debug.Log(weaponObjects);
        List<string> weapons = weaponObjects.Select(x => x.name).ToList();
        weapons.Add("Unarmed");
        Debug.Log("Weapons: " + weapons.Count);
        List<string> components = componentObjects.Select(x => x.name).ToList();
        components.Add("Unarmed");

        ClearExistingOptions();

        //Generate Dropdowns for Repeater Mounts
        for (int i = 0; i < shipData.repeaterMountCount; i++)
        {
            CreateDropdown("Mount " + (i + 1), weapons);
        }
        for (int i = 0; i < shipData.componentCount; i++)
        {
            CreateDropdown("Component" + (i + 1), components);
        }
    }

I am trying to make a dropdown but for some reason my lines 4-8 will not make a proper list. If I don't include the add method (line 5) it will send the object RR-01 as an option, but with the add method, it removes everything and only sends that Unarmed string to the list. Does anyone know the cause for this?

crude mortar
#

@rapid stump Try calling FindObjectOfType<MiniMapController>(true); instead. This will try to find inactive objects as well. Maybe you are disabling it on the first frame or something.

rapid stump
#

Ooo, maybe. Let's see

#

gasp

#

That fixed it

#

You're a god lol

crude mortar
dusk apex
versed spade
versed spade
# crude mortar How are you creating the dropdown? This sounds like the relevant part

This is the creation code:

    private void CreateDropdown(string label, List<string> options)
    {
        GameObject dropdownGo = Instantiate(dropdownPrefab, gridParent);
        dropdownGo.name = label + " Dropdown";
        TMP_Dropdown dropdown = dropdownGo.GetComponentInChildren<TMP_Dropdown>();
        dropdown.ClearOptions();
        dropdown.AddOptions(options);
        dropdown.RefreshShownValue();
        TextMeshProUGUI a = dropdownGo.GetComponentInChildren<TextMeshProUGUI>();
        a.text = label;

    }
crude mortar
knotty sun
versed spade
#

yes. It generates them like so

#

Only item is unarmed. Gonna check the objs

#

Figured it out. Seems I will need to check EVERY little thing of my program when using Unity Version Control as it reset the Weapon Objects list and so nothing would be sent down the chain

inland comet
#

OK so basically I had a particle system that spawned fireflies randomly around the terrain at night. I changed the terrain about a week ago (completely new terrain), and now I don't see the fireflies spawn. There is a prefab called Fireflies, a placement generator script I found online, and then code that turns it off during day and on during night. First screenshot: placement generator script component added onto a scripts empty object. I messed around with "Height of check" and nothing changed. Second screenshot: for loop that plays fireflies at night that worked before, but now it is not even giving me that debug log. Third screenshot is the full placement generator code I found online (I tried searching for it again but could not find it). Im at a complete loss, any ideas?

light pond
#

i tried deleting the library folder and the problem still continues

crude mortar
inland comet
#

yeah update: changed "height of check" again, this time to 20, and now the debug log is printing, but I still cant see them

crude mortar
#

Make sure the height is above the highest point of the terrain, and that the range from that height can hit the lowest point in the terrain. Then make sure that the area (negative / positive positions) is mapped to the dimensions of your terrain. If your terrain is centered in the world, you will have to use the negative dimensions as well (half extents into the negative, and half extents into the positive).

#

If it is actually calling .Play and the Fireflies are spawned in reasonable locations (which you can see by just looking in the hierarchy), then I would look at your particle system and make sure it looks as expected

inland comet
#

Placed a Fireflies prefab in the scene and it looks how it did before. How exactly do I get the lowest and highest point of the terrain? Sorry 😅 I know where to get the width and length at least

#

Got it hellmo Thank you

chilly surge
#

That's not what the error says though

gray mural
rapid stump
#

So this video explains my problem quite well, but in case anyone doesn't want to listen to my voice lol

I'm trying to implement a minimap into my mobile game. The mini map is basically an orthographic camera that feeds its render texture into a raw image UI in a canvas group so the player can see the map.
My problem is the interaction with the map. The player needs to be able to double click on the map and set a destination where they clicked, but I just don't know how to calculate that because of all the factors, the world position of the players click, the world position translated to the map position, the size of the orthographic camera (if that's even a factor) etc.

Idk what to do XD Please help
Here's my current code.
https://pastebin.com/WPC6FUXZ
I attempted to just get the localPosition of the players click relative to the UI image, which the size and scale I know, and translate it to the map position +- the cameras position, since the cameras position is the center of the UI image.
Didn't work, heh...

mild orbit
#

So I am working on a thing to make it easier to add feedback/juice. The idea being that there are pre-made effects (Move object, shake camera, play particle system, etc.), that you can then easily play.

But I am having a hard time deciding on a good API that feels easy to use, and easy to find/select the effect you want.

// A: Not discoverable, feels a little 'raw' to me?
new PositionEffect(0.25f)
    .WithEase(Ease.OutElastic)
    .ToRelative(new Vector3(0, 1, 0))
    .Play(transform);
        
// B: Very discoverable, feels a little verbose?
EffectEngine.Create()
    .PositionEffect(0.25f)
    .WithEase(Ease.OutElastic)
    .ToRelative(new Vector3(0, 1, 0))
    .Play(transform);

// C: Sort of discoverable.
EffectEngine.Create<PositionEffect>(0.25f)
    .WithEase(Ease.OutElastic)
    .ToRelative(new Vector3(0, 1, 0))
    .Play(transform);

// D: Something else?

Anyone got any thoughts or suggestions?

cloud python
gray mural
spring flame
#

Or make them properties and use the Property initialization expression

mild orbit
ocean hollow
gray mural
spring flame
spring flame
#

much better with the named arguments now*

mild orbit
gray mural
mild orbit
ocean hollow
spring flame
spring flame
cloud python
gray mural
dense spear
#

Hey guys!! I am having some trouble with some basic translation and am not sure what am I missing out... so all I want is the projectile to face the direction they are moving in... it basically spawns in the direction of the mouse click and should move in that direction... I was able to rotate the projectile in that direction but the translation doesnt work... am not sure what am I missing out:

Projectile Movement script
    IEnumerator MoveTowardsTarget(Vector2 target)
    {
        float time = 0f;
        target.Normalize();
        while (time < mLifetime)
        {
            transform.Translate(target * Time.deltaTime * mSpeed);
            time += Time.deltaTime;
            yield return null;
        }

        Destroy(this.gameObject);
    }

Spawning the Projectile
    private void Update()
    {
        Vector2 mousePos = Input.mousePosition;
        Vector2 mPos = Camera.main.ScreenToWorldPoint(mousePos);

        if (Input.GetMouseButtonUp(0))
        {

            p = Instantiate(BigProjectilePrefab, transform.position, Quaternion.identity);

            dir = mPos - (Vector2)p.transform.position;

            //angle = Vector2.Angle(p.transform.right, dir);
            // Quaternion rot = Quaternion.AngleAxis(angle, Vector3.forward);
            // p.transform.rotation = rot;
            //p.Init(p.transform.right);

            angle = Mathf.Atan2(dir.y, dir.x) * Mathf.Rad2Deg;
            Quaternion rot = Quaternion.Euler(0, 0, angle);
            p.transform.rotation = rot;
            p.Init(dir);
        }
        if (p)
        {
            txtLog.text = "dir: " + dir + " angle: " + angle;
        }

}
mild orbit
spring flame
gray mural
cloud python
# ocean hollow > I think 😅

yeah, it was long time agosince i looked ad these scripts, idk if it's checkpoint or hitpoints. because both of the players worked alright before

mild orbit
spring flame
#

but at the same thing comes with the Parameter initialization method, they also wrap

mild orbit
spring flame
#

although maybe on the other hand...

#

nah, I think the intellisense looks fine

ocean hollow
spring flame
#

It probably looks the same with named arguments

ocean hollow
#

please please please clean it up

ocean hollow
cloud python
spring flame
ocean hollow
#

so what is you current issue?

mild orbit
spring flame
#

1st rule of Tooster's procrastination checklist:

  • Is what you are currently doing a detail?
    xd
mild orbit
#

Haha, good checklist

spring flame
#

there are like 21 points for my own sanity on that list xD

mild orbit
#

Lol xD

#

Well, thanks for the thoughts 🙂

cloud python
ocean hollow
cloud python
ocean hollow
#

its impossible for me to discern that as is with how bad this code is setup

rocky jackal
#

My unity editor crashed and when i reopened it i got a bunch of these errors that havnt been there before

plain ibex
#

hi everyone are you using any code for your game's compatibility with different devices (for screen edge gaps , object size , object locations , objects outside the screen etc.)

#

its not about canva

#

its about other objects that not in the canva

ocean hollow
elfin tree
#

I want to make a trail renderer go around the edge of a ui element. What would be the best way to go about this?

ocean hollow
# cloud python

you have two of the same debug statement but it is only called once (the one in the hitpoint script is called but not in the checkpoint script)

cloud python
ocean hollow
#

wdym "the same thing"?

cloud python
#

and both of the players have like the same thing, literally

ocean hollow
cloud python
ocean hollow
#

this way the script is a lot more neat and easy to understand

#

now use this version of your script and debug it if it doesnt work

cloud python
#

ok, imma try it

dusk apex
#

Error says Check Point 46

ocean hollow
#

it should be "Player Manager"

cloud python
#

ok

ocean hollow
ocean hollow
cloud python
#

ok

cloud python
ocean hollow
vivid remnant
#

Apologies for interrupting. :)))
How can I make a rigidbody based character controller handle steps properly and walk up and down stairs smoothly?

spring creek
#

And it only looks like stairs

vivid remnant
#

I thought about that but it feels like cheating.

spring creek
vivid remnant
#

The kinematic character controller seems way to complicated IMO.

elfin tree
#

Is there a way to add padding when using stretch?

ocean hollow
normal arch
#

Hey guys! I'm making a game with an Earthbound style encounter system, there are enemies in the overworld, and if you come into contact with any of these enemies a fight starts. However in Earthbound if you come into contact you might encounter more than one enemy, and not necessarily the same type of enemy

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

public enum Biome
{
    spring,
    beach,
    forest,
    mountain
}

public class BattleTrigger : MonoBehaviour
{
    public EnemyObject enemy;
    public Biome biome;

    void OnTriggerEnter2D()
    {
        BattleRelayInfo.instance.Relay(enemy, biome);
        SceneManager.LoadScene("BattleScene");
    }
}

I currently have this script rn and was wondering how I could change it to achieve what I want, does anyone know how?

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

public class BattleRelayInfo : MonoBehaviour
{
    public static BattleRelayInfo instance;
    public EnemyObject enemy;
    public Biome biome;
    void Awake()
    {
        if (instance == null) 
        {
            instance = this;
            DontDestroyOnLoad(this.gameObject);
        }
        else 
        {
            Destroy(this.gameObject);
            return;
        }
        instance = this;
        DontDestroyOnLoad(this.gameObject);
    }

    public void Relay(EnemyObject enemy, Biome biome)
    {
        this.enemy = enemy;
        this.biome = biome;
    }
}

this script is also involved

buoyant vault
#

Hi guys, is it alright to ask around here about my problem in navmesh?

buoyant vault
normal arch
honest trout
#

can anyone help me with this? basically i made Controls and for some reason it keeps giving this error

private void LateUpdate()
  {
     look.ProcessLook(onFoot.Look.ReadValue<Vector2>());
  }```

heres the script
honest trout
ocean hollow
#

there is no "look" method

honest trout
#

there is though

#
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;

public class InputManager : MonoBehaviour
{
  private PlayerInput playerInput;
  public PlayerInput.OnFootActions onFoot;

  private PlayerMotor motor;
  private PlayerLook look;

  void Awake()
  {
    playerInput = new PlayerInput();
    onFoot = playerInput.OnFoot;
    motor = GetComponent<PlayerMotor>();
    look = GetComponent<PlayerLook>();
  }

  void FixedUpdate()
  {
    motor.ProcessMove(onFoot.Movement.ReadValue<Vector2>());
  }
  private void LateUpdate()
  {
     look.ProcessLook(onFoot.Look.ReadValue<Vector2>());
  }

  private void OnEnable()
  {
    onFoot.Enable();
    onFoot.Jump.performed += ctx => motor.Jump();
  }

  private void OnDisable()
  {
    onFoot.Disable();
  }
}
#

here's the full script

normal arch
#

I think you need to look at the OnFootActions script

ocean hollow
leaden ice
#

Anyway your problem is in your input action asset

#

You probably didn't name things the same way as the tutorial

honest trout
#

i see

honest trout
#

the jump script wasn't working and we needed to do something way different to make it work

leaden ice
#

You have a simple naming problem here

#

If you didn't name the action Look it won't be called that in the code

honest trout
#

can i be because of this action not having a name?

leaden ice
#

Yes

#

That's what I just said

buoyant vault
#

I think you should watch and follow the tutorial exactly and then freestyle when you get the hang of it my guy. That way you won't get lost in the sauce

leaden ice
#

The code is expecting you made an action called "Look" like in the tutorial

honest trout
#

Renamed it into "Look" what should i do now?

leaden ice
#

Save the asset

#

And it will work

honest trout
#

Yes it worked, thank you so much.

normal arch
buoyant vault
normal arch
#

no it's not that, I already have that down, it's that I want there to possibly be multiple enemies passed along with each trigger

buoyant vault
#

ohhh ok gotcha because the code you made can only send one

cloud python
buoyant vault
#

I mean you could just pass a List<EnemyObject > instead of just one EnemyObject... I think sadok

ocean hollow
normal arch
knotty sun
normal arch
knotty sun
normal arch
knotty sun
#

no idea, outside the scope of your question

normal arch
#

What I was saying is that I wanted to have a list with two values kind of, an EnemyObject, and a spawnChance

buoyant vault
#

ohhh

normal arch
#

i tried a Dictionary but you can't see those in the inspector i don't think

normal arch
#

You can't view tuples in the inspector and I would have to manually assign these in the Inspector, there's no other way, so how would I do that?

somber nacelle
#

Make a struct that holds those objects

normal arch
#

sorry, I'm not familiar with structs

buoyant vault
#

I think its just a little confusing. do you want to do something like (Logic Wise)

100%
BattleRelayInfo.instance.Relay(biome, enemy1);

20%
BattleRelayInfo.instance.Relay(biome, enemy1, enemy2);

5%
BattleRelayInfo.instance.Relay(biome, enemy1, enemy2, enemy3);

#

ohh sorry my bad you also want it to be editable in Inspector

#

my guess is you want to be able to play around with the values in inspector. Like being able to put 10% as 4 enemies or 25% chance of 8 enemies but all in inspector right?

normal arch
normal arch
#

Sorry I think i read it wrong, I want there to be a list of enemies, with each enemy having a certain probability of spawning, and I want it to be editable in the inspector

#

I'm not sure if that's possible or not

cloud python
buoyant vault
normal arch
#

ok, ty

hexed fjord
#

I think the chance thing can be a simple array

buoyant vault
# normal arch ok, ty

[Serializable]
public struct EnemySpawn
{
public EnemyObject enemyObject;
public int chance;
}

here you go my guy

#

should be something like this

#

my bad dont forget:

public List<EnemySpawn> EnemySpawnList;

normal arch
#

did i do something wrong

buoyant vault
#

put the [Serializable] ontop

normal arch
#

OHHHH

#

tysm

buoyant vault
#

dont worry @hexed fjord took us a while to understand the requirements sadok

buoyant vault
# normal arch OHHHH

do note tho that can only spawn ONE enemy per chance rolled. so if ever you want a more flexible amount of enemies being spawned per roll

just use
public List<EnemyObject> enemyObject;
isntead of
public EnemyObject enemyObject;

hexed fjord
#

Im late but this is what i was making

public GameObject[] enemies;
public int[] spawnChance;
//You set the probabilities from biggest to lowest, but adding all before it
//For example: 80 (80%), 90 (10%), 95 (5%), 100 (5%)

void SpawnFunction(){
  int rand = Random.Range(1, 101); //Gives a value from 1-100
  for(int i=0; i<spawnChance.Lenght; i++){
    if(rand <= spawnChance){
      //Spawn this enemy and all before it in the array
      for(int k=0; k<=i; k++){
        //Spawn enemies[k];
      }
    }
  }
}
normal arch
#

now i just need to know how to use probability to do this

buoyant vault
#

just do something scuff like
Random.Range

normal arch
#
public void SpawnEnemy()
    {
        for(int i = 0; i < enemies.Count; i ++)
        {
            GameObject log = Instantiate(enemies[i].enemyObject.enemyPrefab, enemySpawnPoint.position, Quaternion.identity);
            Log logScript = log.GetComponent<Log>();
            logScript.target = player.transform;
            logScript.moveSpeed = 2;
            logScript.attackRadius = 1;
            logScript.anim = log.GetComponent<Animator>();
            logScript.myRigidbody = log.GetComponent<Rigidbody2D>();
        }   
    }

i just want to do this but with the prob stuff

#

also the script is scuffed because it only allows one enemy type

#

but ill ignore that for now

buoyant vault
#

you can change
public List<EnemyObject> enemyObject;
to
public List<GameObject> enemyObject;
so you can put different prefabs instead

or
public List<MonoBehaviour> enemyObject;
for scripts

buoyant vault
normal arch
#

all enemies should derive from an Enemy script, it's just that all the variables are different, for the ones that are different i think I should just use a scriptable object

buoyant vault
#

ah I see yeah this time it can go alotta ways. Have fun experimenting haha

normal arch
#

ty for the help, it's done a lot

cloud python
# cloud python

I guess it must be something with where i put the debug or something. and the fact it didn't debug the backfull health thing

lunar kestrel
#

Guys do you know how to optimize shadowcasters2d? I have a lot of them in different areas and I was thinking about making circle cast every frame
and turning on only ones in the visible range of player, how can I do that?

leaden ice
lunar kestrel
#

or is unity already doing that?

leaden ice
#

.617ms is not the end of the world

#

you typically have a 17ms frame budget

elfin tree
#

How come two rigidbodies on layers that should not collide still enter in collision, is that the expected result?

#

Also tried manually specifying it with Physics.IgnoreLayerCollision

#

nvm

leaden ice
#

not expected no.

somber tapir
#

Why do both Debugs fire here when I start the game in the Editor?

knotty sun
cloud python
# cloud python

does it something to do with if (player2D != null) ?

Player2D is a script that is for the players

as long I'll wait till the respond

stable lintel
#

is there a way to make grass zones for procedural generation

#

using unity terrain

wispy raptor
#

is there a fix or solution to "waiting for unity code to finish executing" ?? for some reason that appears and unity never enter to playmode

somber nacelle
#

sounds like you have an infinite loop in your code

shell scarab
#

Why am I getting Assertion failed on expression: 'CurrentThreadIsMainThread()' from JsonUtility.ToJson if ToJsonInternal has the ThreadSafe attribute? Unless that attribute actually means it needs to be on the main thread?

wheat kraken
#

Uhhhhh, Has anyone got any ideas?

rigid island
#

make sure you're passing a string

shell scarab
# wheat kraken Uhhhhh, Has anyone got any ideas?

try laptime.ToString().

This confused me when first starting out coding and w/ unity. Unity's Debug.Log takes an object so you can pass anything into it and it converts it to its string representation. I got used to that, and when I first encountered a situation where I needed to pass a number as a string I was confused.

shell scarab
wheat kraken
shell scarab
wheat kraken
#

Besttime

shell scarab
#

what type is Besttime?

simple egret
#

You set bestTime to lapTime right before writing to the file, so it's normal that they're equal

shell scarab
# wheat kraken Besttime

does it literally write "Besttime" or does it write the value of besttime? The way you worded it made it sound like it's writing "Besttime" to me.

rapid stump
#

So this video explains my problem quite well, but in case anyone doesn't want to listen to my voice lol

I'm trying to implement a minimap into my mobile game. The mini map is basically an orthographic camera that feeds its render texture into a raw image UI in a canvas group so the player can see the map.
My problem is the interaction with the map. The player needs to be able to double click on the map and set a destination where they clicked, but I just don't know how to calculate that because of all the factors, the world position of the players click, the world position translated to the map position, the size of the orthographic camera (if that's even a factor) etc.

Idk what to do XD Please help
Here's my current code.
https://pastebin.com/WPC6FUXZ
I attempted to just get the localPosition of the players click relative to the UI image, which the size and scale I know, and translate it to the map position +- the cameras position, since the cameras position is the center of the UI image.
Didn't work, heh...

wheat kraken
shell scarab
wheat kraken
#

enum?

#

its a float, but that line converts it to a string

simple egret
#

Show your updated code, a float converted to a string does not return the variable name it was in

wheat kraken
#

This is it.

shell scarab
#

what is "BestTime"?

#

can you show where all your fields are defined?

simple egret
#

BestTime looks like another variable you haven't told us about yet

wheat kraken
#

ooooo

simple egret
#

(that's why you don't name them so similarly)

wheat kraken
#

wait that could be the issue

#

nah didnt write anything that time

wheat kraken
wheat kraken
simple egret
#

It's never too late, VS provides tools to rename things and reflect the changes everywhere the name is used

shell scarab
wheat kraken
shell scarab
#

yea, so BestTime is a UI element, so it looks like it's printing the text it contains

rigid island
wheat kraken
#

its for my computer science coursework, one of the things on teh mark scheme says to comment my code

rigid island
#

They should teach you good code generally comments itself lol

shell scarab
shell scarab
wheat kraken
wheat kraken
shell scarab
wheat kraken
#

so i should put besttime?

shell scarab
# rapid stump So this video explains my problem quite well, but in case anyone doesn't want to...

can you perhaps get the texel coordinate where you clicked, normalize that, then use ViewportPointToRay on the camera that renders to the render texture to raycast?

For example (pseudocode, I wrote this in discord, I hope you get the idea of it), something like this:

RectTransform r = mapImage.GetComponent<RectTransform>()
if(RectTransformutility.ScreenpointToLocalPointInRectangle(r, Input.mousePosition, Camera.main, out Vector2 point)) {
  
  x = ((point.x - r.x) * mapImage.width)/r.width;
  y = ((point.y - r.y) * mapImage.height)/r.height;

  Ray ray = mapCamera.ViewportPointToRay(new Vector3(x, y, mapCamera.nearClippingPlane);
  // do your raycast stuff from here
}
wheat kraken
#

(Old screenshot by accident so ig 'trust me bro')

signal wadi
#

Hey guys, I have a game manager script that is persistent. How can I make sure the references between levels (unity events) are not lost when the level switches?

dusk apex
signal wadi
# dusk apex What do you mean by making sure they're not lost? Do both persist between scenes...

So let's say my GameManager handles a method called LoadScene(string sceneName)

I use unity events so when the player from the main menu clicks "Play Game", it fires LoadScene("Level1")

Okay so it does exactly that woohoo. But then it gets to Level1 and the player wants to return to the menu. GameManager, which is persistent, cannot be referenced on the "Back to menu" button because it didn't exist already in that level, only MainMenu.

#

I can reference the level objects in static fields. But the issue is they are not serialized and that's really what I am aiming for.

#

The reason a method like GameManager.LoadScene(string sceneName) exists is again, due to serialisation

wheat kraken
#

Ok why does this not work

#

it doesnt write to the text file, when that should

somber nacelle
#

well that certainly doesn't look like a valid path

#

also the Assets folder will not exist inside of a build, consider writing to Application.persistentDataPath instead

wheat kraken
signal wadi
#

Okay well I guess I can extend my question to: How do I handle levels in a game with many scenes?

If you read my question it gives you an idea of how I treat it now, any better way?

rigid island
wheat kraken
#

let me find it

#

But that didnt work

#

it did not save anything to teh txt

somber nacelle
#

because you somehow made it even worse

wheat kraken
#

Can someone just tell me what to put 😭

rigid island
signal wadi
wheat kraken
somber nacelle
#

that is the persistentDataPath

#

that folder you are currently viewing is what Application.persistentDataPath returns the path for

wheat kraken
#

Im confused....

#

And i should'nt be

somber nacelle
#

did you know that it generally helps to ask questions about what you are confused about instead of assuming someone will read your mind to know what it is that needs explaining?

signal wadi
#

Windows Editor and Standalone Player: Application.persistentDataPath usually points to %userprofile%\AppData\LocalLow\<companyname>\<productname>. It is resolved by SHGetKnownFolderPath with FOLDERID_LocalAppDataLow, or SHGetFolderPathW with CSIDL_LOCAL_APPDATA if the former is not available. From the docs navarone said

somber nacelle
#

this is Windows Editor and Standalone Player (considering this is in editor)

signal wadi
#

The whole thing can be avoided by just reading the docs

wheat kraken
#

i did

#

and i didnt understand it

somber nacelle
#

so then what are you confused about

wheat kraken
#

Why it isnt writing to the file

#

it isnt throwing errors

somber nacelle
#

show your current code and what you've done to ensure that the code is actually running

wheat kraken
somber nacelle
#

!code

tawny elkBOT
somber nacelle
#

also wtf why are you hardcoding the path like that. navarone literally gave you the code to create the path using Application.persistentDataPath

rigid island
#

wild

wheat kraken
rigid island
#

use link sites

rapid stump
wheat kraken
#

yeah - ill use pastebin

heady iris
#

RectTransform is a child of Transform

wheat kraken
somber nacelle
#

if you're going to use pastebin, at least have the courtesy of selecting the language so there's syntax highlighting

rigid island
shell scarab
somber nacelle
# wheat kraken https://pastebin.com/pFu4FWZP

and again, what are you actually doing to ensure that the line of code that writes to the file actually runs. you didn't bother putting any debugs in here, and with your complete lack of understanding of how to get a real path, i assume you also don't know how to use breakpoints in your code editor

shell scarab
#

basically you're trying to create a viewport point out of the location you clicked on of the image. A viewport point is 0-1, so normalizing the point you clicked on in the image to be 0-1 as well will give you a viewport point.

heady iris
#

Oh, you want the rect :p

wheat kraken
rigid island
#

no idea why you hardcoded that path

somber nacelle
#

also there is nothing at all that would be updating when that line runs

heady iris
#

when you assume, you make an "ass" out of "u" and "me" (:

#

assumptions lead to hours of wasted time

rigid island
#

"measure twice, cut once"

wheat kraken
#

Well, i guess i have learnt a valuable lesson

#

The debug.log did not run

shell scarab
somber nacelle
wheat kraken
#

none of that code is being read

spring creek
#

Woof that path

somber nacelle
# wheat kraken none of that code is being read

it's not that the code isn't being read, because nothing here is doing any reading. it's that either you have an error in your console that is being ignored or that code is not actually running

simple egret
#

That's just the persistent data path isn't it

somber nacelle
#

yep. we told them to use Application.persistentDataPath and navarone even gave a line of code that would create the path using that.

#

this was the result of that advice (but hey, at least they aren't trying to write to C:\Assets now)

wheat kraken
somber nacelle
#

screenshot the entire console window

wheat kraken
spring creek
# wheat kraken

Soooo... you do have errors that should be addressed.
But you cropped off part of the console

#

The important part on the top right

shell scarab
# wheat kraken

well you seem to have Non-convex mesh colliders with non-kinematic rigid bodies. Why are you even using mesh colliders 0.o

spring creek
#

What number does it say for errors

rigid island
#

also not scrolled all the way down

rapid stump
wheat kraken
shell scarab
wheat kraken
#

I know the box collider is not an issue as its a trigger and everything else it is assigned to do works and activates when it is touched

somber nacelle
#

honestly there is just so much wrong with the logic here. it is going to be a real pain in the ass to figure out what is wrong with it.
one of the worst things you are doing is relying on gameobject names for your logic

rigid island
wheat kraken
#

including the stuff that is in the same script

wheat kraken
rigid island
#

yeah agreed with boxfriend, soo much can go wrong there

simple egret
#

Seems like the piece of code that writes to the file is nested in another block { }, maybe it's an if statement whose condition never passes...

rigid island
#

is LapTimeCheckpoint even the character /vehicle ?

wheat kraken
#

I moved this out of the { } and i got an error with the path 💀

#

saying it cant find the path

shell scarab
rigid island
#

but also how they understand 0 of their own code

simple egret
neon glen
#

im trying to make a mobile game and im just confused on one thing. Scale. When im in the editor with my game and i play the borders ive made with a game object are fine but when i build to my test phone the borders arnt there and they are off screen. I dont understand how to get game objects to transform ocrding to the device res

shell scarab
#

also I've tried AI-generated code in the past (not copilot yet, gonna try that this summer), and it does things like other.gameObject.name == "checkpoint2"

wheat kraken
simple egret
#

Yes, just make sure you do both in the end

wheat kraken
rapid stump
# shell scarab you should be able to use the Image component I believe. Like the thing that ren...

Yeah idk anymore XD
https://pastebin.com/xsyuud3F
The mapImage is the NewMap which is 1000x1350, the image the player interacts with to move and zoom the camera.
And it's coordinates are way off when the player double clicks

shell scarab
neon glen
shell scarab
wheat kraken
#

welp i got it working

shell scarab
untold grotto
#

Anyone wanna share the gravity and initialJumpVelocity values that work for you?

#

Just curious

rapid stump
# shell scarab probably something wrong with my code (i wrote it in here), but what's set desti...
    public void SetDestinationMarker(Vector2 Pos)
    {
        destinationPositionBool = 1;
        destinationPosition = Pos;
        destinationMarker.gameObject.SetActive(true);
        // Set the destination marker's position
        destinationMarker.transform.localPosition = destinationPosition;

        // Start moving the ship towards the destination
        isMoving = true;

        // Update travel time text
        UpdateTravelTime();
    }

This is what it does. It basically sets my DestinationMarkers localPosition as the inputted position after the calculation and then activates it.
The destinationMarker is a child of my minimaps worldSpace canvas. So it its position is 700X 800Y, that is it's possible compared to the minimap

shell scarab
rapid stump
#

Ohhhhhhhh

soft shard
# untold grotto Anyone wanna share the gravity and initialJumpVelocity values that work for you?

I think your question needs more context, what is it your trying to do or solve? What are those values your referring to? And what system are they meant to be a part of? There are many ways to build a system, so just simply copying someone elses values may not solve whatever problem your currently having with your system, if your system is not coded and setup the exact same way as someone providing those values

untold grotto
#

I'd like for it to last, so that I can see the parabola and it feels a bit smooth if that makes sense

lean sail
#

i suspect some rb and unneccesary Time.deltaTime usage

untold grotto
#
    {
        Vector3 newMovementDirection = new Vector3(_psm.playerInputManager.inputMovement.x, 0, _psm.playerInputManager.inputMovement.y);
        if(newMovementDirection.magnitude > 0){
            _psm.movementDirection = newMovementDirection;
        }
        _psm.speed += newMovementDirection.magnitude > 0 ? _psm.acceleration : _psm.decceleration;
        clampSpeed();
        _psm.playerAnimationManager.updateParameter(0, _psm.speed);
        handleGravity();
        Vector3 finalMovement = _psm.movementDirection * _psm.speed + new Vector3(0, _psm.ySpeed, 0);
        Debug.Log(finalMovement);
        _psm.playerCharacterController.Move( finalMovement * Time.deltaTime);
    }

    private void handleGravity(){
        _psm.ySpeed += _psm.gravity;
    }```
#

here _psm.speed refers to the XZ plane speed

#

which is also the same when I am on the ground

lean sail
#

first thing i notice is that your handle gravity logic doesnt use deltaTime, which is probably why your jump is done so fast

untold grotto
lean sail
#

assuming logic() is called every frame

untold grotto
#

makes sense, that v = u+a*t

#

Thanks

reef garnet
#

Hi I'm working on a controller where movment is based on the gravity direction as gravity direction will change dynamically:

#

To further explain, my gravity will always be the players y axis as far as movement goes, how do I move in the perpendicular x and z axes if y is changing

vagrant blade
#

You can look up the concept of the cross product, which is how you calculate perpendicular vectors.

#

Fortunately, Unity has a built in Vector3.Cross utility function

reef garnet
#

I've been looking into using the Cross product, just been messing up which directions to use to get my desired result

#

maybe between gravity direction and camera.up?

#

I'll try it

vagrant blade
#

It would be the gravity direction and the forward direction of the player

reef garnet
#

I'm building a sort of Gravity Rush style game so the player's forward may not be a reliable source

vagrant blade
#

You have its movement direction though, which you can use as the forward at least. Make sure you're normalizing your vectors as well before you cross them.

reef garnet
#

thanks

grizzled ibex
lament helm
#

Ty

grizzled ibex
hazy pike
#

hello guys, I'm trying to create a crafting system in my game. Basically I interact with an object and then a UI appears with for example 3 slots 2 for the inputs one for the output but this is the first time I make something like that and I can't really wrap my head around it.

#

I already have a functional inventory system, 4 slots that holds scriptable objects called item

soft shard
hazy pike
fervent furnace
#

there must be a upper bound of slot number (otherwise imagine you can have a 2147483648 slots)

#

no idea what you are asking, if you are asking how to UI interaction then i cant answer you....
but if you are asking how to check the input pattern/give suggestions based on input then tree can solve it

hazy pike
#

I guess I will try to do something and come back with a better question because each time I do something I am just like nah and I delete it all

lean sail
# hazy pike I guess I will try to do something and come back with a better question because ...

split it up by steps, with 4 slots or even a short list of craftable items you could do pretty much anything to get a list of craftable ingredients based on an inventory. If you plan on having a large list of craftable stuff, then id worry about efficiency. This still doesnt affect other code, its still outputting the same thing
Then worry about the UI which at the end of the day, hooks up a button to a method. That method will take items and spit out the item

vestal arch
#

I haven't done unity for a hot while and I feel like I might just be missing something...
I have a prefab with a rigidbody2d, and i'm dynamically instantiating it and setting a velocity to it.
The prefab gets instantiated, but the velocity is always 0. I've logged out the vector i'm using and it's not 0. I've tried setting the velocity after the instantiation and in a Start on the prefab.
Am i just forgetting something?

#

the code is just a rigidbody.velocity = new Vector2(...);

crude mortar
cosmic rain
vestal arch
#

I'll have to be back in a bit then

spring creek
#

Oh, you said the velocity setting is in start. So it wouldn't be the second guess

vestal arch
#

the rigidbody is dynamic, i recall checking that

#

the instantiation is here, i used to have the velocity setting here and it didn't work either```cs
private IEnumerator<YieldInstruction> SpawnProjectile() {
while (true) {
yield return new WaitForSeconds(projectileSpawnInterval / 2);
GameObject projectile = Instantiate(projectilePrefab);
projectile.transform.position = transform.position;
yield return new WaitForSeconds(projectileSpawnInterval / 2);
}
}

#
    public void Start() {
    // public void Update() {
        Vector2 position = transform.position;
        Vector2 target = player.transform.position;
        float angle = Mathf.Atan2(position.y - target.y, position.x - target.x);
        Debug.Log(angle);
        Debug.Log(new Vector2(
            Mathf.Cos(angle),
            Mathf.Sin(angle)
        ) * speed);
        // WHY?????
        rigidbody.velocity = new Vector2(
            Mathf.Cos(angle),
            Mathf.Sin(angle)
        ) * speed;
        StartCoroutine(Expire());
    }
```this is the entire start method on the prefab, and the logs are hit and show non-zero values
quartz folio
#

IEnumerator<YieldInstruction> this is not how you properly declare a coroutine

#

Just use IEnumerator

#

You immediately set the transform's position, which may override its velocity

#

you should use the instantiate overload that takes a position (and rotation)

vestal arch
#

that makes a lot of sense

#

yeah i'll try looking into that

vestal arch
quartz folio
#

Coroutines in Unity are old and integrated with unmanaged code, it's just how it's done

hazy pike
vestal arch
quartz folio
#

If it works, I can't imagine there are any. It's not the way it's written in any docs or code I've seen though, so I wouldn't be surprised to find it didn't

vestal arch
#

it's been working fine for me

quartz folio
#

Then I've learnt a new useless fact 😄

vestal arch
#

i'll probably just use this then to satisfy my java brain lol

knotty sun
#

Hey, If this is not code related why are you posting in a code channel?

lavish wren
#

but tell me ill move it

knotty sun
vestal arch
crude elm
#

Does anyone know why the result of InverseTransformVector() method may not match the manual calculation using rotation and position of that transform?

var altLocalVector = math.mul( math.inverse( transform.rotation ), vector - transform.position );```
late lion
crude elm
plain ibex
#

Is atan means arc tan ?

fervent furnace
spice briar
#

hey everyone, im trying to make an AI enemy that shoots in bursts.
The issue im having is that canShoot is always true, and while the cooldown isnt happening the enemy shoots a bullet every frame instead of using the Invoke() to reset it.

#
if (canSeePlayer)
{
    timeSincePlayerSeen += Time.fixedDeltaTime;
    eyePos.forward = lastPositionPlayerSeen - transform.position;

    if (timeSincePlayerSeen == 0)
    {
        CooldownShot();
        ResetShot();
    }

    //if (timeSincePlayerSeen < reactionTime) canShoot = false;

    if (canShoot && roundsLeftInBurst > 0)
    {
        Instantiate(bulletPrefab, eyePos.position, eyePos.rotation);
        canShoot = false;
        roundsLeftInBurst--;
        //Invoke(nameof(ResetShot), 50/650);
        Invoke(nameof(ResetShot), 0.25f);
    }
    if(roundsLeftInBurst <= 0)
    {
        canShoot = false;
        Invoke(nameof(CooldownShot), cooldown);
        Invoke(nameof(ResetShot), cooldown);
    }
}```
#

this is happening inside FixedUpdate but ive tried Update as well

cloud python
knotty sun
fallow quartz
#

When im working with a canvas why sometimes i can make bigger stuff from it only by dragging and other times i just cant do it, just if i was using a normal gameobject?

spice briar
#

so it will be zero

#

though i should put that before i += it....

opaque forge
#

Hey I want to instantiate various objects randomly. How can I check if an object is already placed at the position so that I don't spawn one if there is?

spice briar
#

and that isnt the issue here

knotty sun
spice briar
#

cant fit it into 1 message

knotty sun
#

that is why we have !code

tawny elkBOT
knotty sun
#

use a paste site

spice briar
#

seems like the first burst works

knotty sun
soft shard
ocean hollow
#

this looks like a huge waste of time if you dont know basic coding principles

surreal cloak
#

so i am setting up footsteps with a script and i checked the script and idk whats causing the footsteps to bug out. It plays like on or two and then it plays like a very very silent click if i can even call it a click. A very and i mean very silent sound instead of a footstep. Idk how to rightly configure audio but i have tried setting its priority to both the highest and the lowest. ```
[Header("References")]
public AudioClip[] footsteps;

[Header("Attributes")]
public float stepInterval = 0.6f;
[Range(0, 1f)] public float stepWidth = 0.3f;

private AudioSource audioSource;
private bool isWalking;
private bool waitingForStep;
private bool rightStep = false;

void Start()
{
    audioSource = gameObject.GetComponent<AudioSource>();
}

void Update()
{
    isWalking = Input.GetButton("Vertical") || Input.GetButton("Horizontal");

    if (isWalking && !waitingForStep)
    {
        StartCoroutine(WaitForStep());
    }
    else if (!isWalking)
    {
        waitingForStep = false;
        StopAllCoroutines();
    }
}

void TakeStep()
{
    int newStepIndex = Random.Range(0, footsteps.Length);

    if (rightStep)
    {
        audioSource.panStereo = stepWidth;
    }
    else
    {
        audioSource.panStereo = -stepWidth;
    }

    audioSource.clip = footsteps[newStepIndex];
    audioSource.Play();

    rightStep = !rightStep; 
}

IEnumerator WaitForStep()
{
    while (isWalking)
    {
        TakeStep();
        waitingForStep = true;
        yield return new WaitForSeconds(stepInterval);
        waitingForStep = false;
    }
}

}

fallow quartz
soft shard
# surreal cloak so i am setting up footsteps with a script and i checked the script and idk what...

Sounds like your audio may be overlapping, which suggests you may be calling your functions more often than you think, try adding a Debug log to the start of your coroutine outside your while loop to make sure its only being called once, and inside your TakeStep function to make sure its being called the correct number of times as well, if those logs spam, you know your function is being called as often as the logs are

cloud python
ocean hollow
#

what exactly isnt working, from what you understand?

cloud python
# ocean hollow so can you tell me why you think this is happening?

I don't know why it is not working, from what I'm saying, when I die by losing all of my health and lose a life, I'm supposed to respawn to where the checkpoint is and my health is suppsoed to be back to full health, but instead when I Die by losing all of my health and when I respawn from the checkpoint, my health isn't back to full health, and I am stuck in midair and I cannot move anywhere,

ocean hollow
#

figure out why this is

cloud python
ocean hollow
#

you will never debug your code this way and you cannot expect others to do it for you

#

please learn c# and come back

surreal cloak
cloud python
ocean hollow
#

you arent "stupid", youre just expecting things to magically work and for information to enter your brain without studying or practicing

surreal cloak
ocean hollow
#

just a few hours should be enough

rapid stump
#

https://pastebin.com/fxXd7SvW

I'm losing my mind here. The video explains my problem, but incase you don't want to watch it.
I'm trying to make a minimap for my game using an orthographic camera looking at a Canvas UI in world space that is 10,000x10,000. Which is my map. The orthographic cameras render images are fed into a raw image that the main camera can see. And I have it so the player can move the camera around/pan the camera as they drag on that raw image. And even scale the orthographic camera, by changing its size so they zoom in/out.

But now my problem is, calculating the position of the plays mouse click on the raw image, relative to the maps position. I don't know how to do that, at all. I need to somehow, using just the position of their mouse click relative to my raw image transform, translate that to my maps position so my other map script c an handle the logic of setting the players destination WHERE they clicked.

#

I am currently the definition of insanity XD

cloud python
ocean hollow
#

you dont even know how to call functions at all

#

if you follow a beginner tutorial, you will know how to do that

cloud python
ocean hollow
ocean hollow
#

you are going to get nowhere like this

cloud python
ocean hollow
#

youre finding it but not doing anything

cloud python
craggy oyster
#
int nextRoom = Random.Range(1, 5);
            for (int tries = 0; tries < maxRoomTries &&  
                ((nextRoom == 1 && Physics2D.Raycast(new Vector2(currentRoomPos.x, currentRoomPos.y), Vector2.up, distBtwRooms, roomLayerMask)) ||
                (nextRoom == 2 && Physics2D.Raycast(new Vector2(currentRoomPos.x, currentRoomPos.y), Vector2.right, distBtwRooms, roomLayerMask)) ||
                (nextRoom == 3 && Physics2D.Raycast(new Vector2(currentRoomPos.x, currentRoomPos.y), -Vector2.up, distBtwRooms, roomLayerMask)) ||
                (nextRoom == 4 && Physics2D.Raycast(new Vector2(currentRoomPos.x, currentRoomPos.y), -Vector2.right, distBtwRooms, roomLayerMask)))
                ; tries++)
            {
                nextRoom = Random.Range(1, 5);
            }

            CreateRoom(nextRoom);
#

save my sould ive been trying to fix this for 2 days straight

#

im making a dungeon generator and checking if theres a room where im trying to spawn next room using raycast

ocean hollow
craggy oyster
#

but for some reason it still spawns rooms ontop of rooms

gusty monolith
#

I am your favorite son @ocean hollow

leaden ice
ocean hollow
craggy oyster
craggy oyster
#

i should prob make a list to where i spawn tiles right

leaden ice
#

Just save your rooms in the grid and check if there's something in the grid. Use a 2D array or a Dictionary<Vector2Int, Room>

craggy oyster
#

and loop through it when checking where to place next tile

#

yupp

leaden ice
#

no need to loop

#

look up by coordinate

ocean hollow
#

with this being said, i am done helping you

craggy oyster
ocean hollow
craggy oyster
#

i only know the contains function

#

is that what ur talking about

cloud python
cloud python
#

...I just don't know why the function is not being called...

ocean hollow
#

learn to code properly...

cloud python
#

can I just get help from someone else?

leaden ice
ocean hollow
#

you can try

leaden ice
#

YOu absolutely wouldn't use a List here @craggy oyster

#

it should be an array, a Dictionary, or a HashSet

craggy oyster
leaden ice
#

a List will be much too slow

craggy oyster
#

really

leaden ice
#

it's insane to look through the entire list when you know exactly which coordinate you want to check

#

it will be extremely slow

cloud python
# ocean hollow learn to code properly...

before this, when I hade my other coding script. everything worked perfecly fine that I can respawn and move that the full health back, but during some changes around in other scripts and during that.... this happen

craggy oyster
#

i used lists for this sort of grid based maps many times before

leaden ice
#

that's... madness

cloud python
craggy oyster
#

guess thats why i quit the projects for performance issues

leaden ice
#

yes

#

indeed

craggy oyster
#

thanks man!

leaden ice
craggy oyster
#

yea i get it

spring creek
craggy oyster
#

i wasnt aware of the contains i think or i couldnt get it to work before i dont remember

#

thats why i used lists from that point

cloud python
cloud python
smoky tinsel
#

!vscode

tawny elkBOT
#
Visual Studio Code guide

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

https://on.unity.com/vscode

craggy oyster
#

oh nvm praetor

#

i used to use 2d arrays

#

i just forgot lol

spring creek
# cloud python here

Well for one thing, you have if (!isPlayer1) before resetting the hit points. But it looks like no corresponding code for when you ARE player1

cloud python
#

hmmm... no corresponding when I'm player1

cloud python
cloud python
spring creek
#

It's a bit hard to follow though. Lots of dependencies and allll those find calls

cloud python
cloud python
craggy oyster
#
            if((nextRoom == 1 && spawnedRooms[(int)currentRoomPos.x][(int)currentRoomPos.y + distBtwRooms] != null) ||
                (nextRoom == 2 && spawnedRooms[(int)currentRoomPos.x + distBtwRooms][(int)currentRoomPos.y] != null) ||
                (nextRoom == 3 && spawnedRooms[(int)currentRoomPos.x][(int)currentRoomPos.y - distBtwRooms] != null) ||
                (nextRoom == 4 && spawnedRooms[(int)currentRoomPos.x - distBtwRooms][(int)currentRoomPos.y] != null))
            {
                nextRoom = Random.Range(1, 5);
            }
#

@leaden ice its giving me null reference error

leaden ice
#

spawnedRooms is null

#

also this is a jagged array

#

not a 2d array

craggy oyster
#

i have to initialize the 2d array with elements

gusty monolith
#

dipshit

leaden ice
#

you should use a 2D array

#

you did a jagged array so you'd have to initialize each subarray

#

2D array won't require that

craggy oyster
#

this is where i got lost last time i did this

spring creek
craggy oyster
#

i think this guy was trynna insult me

gusty monolith
#

sorry i confused the server

#

i thought i was on another server

leaden ice
#

Sorry the "random insults" server is next door

gusty monolith
simple egret
#

Wrong server, still

craggy oyster
#

its still giving me null reference

#

even with 2d array

leaden ice
spring creek
leaden ice
#

did you actually create the array??

craggy oyster
#
            if((nextRoom == 1 && spawnedRooms[(int)currentRoomPos.x,(int)currentRoomPos.y + distBtwRooms] != null) ||
                (nextRoom == 2 && spawnedRooms[(int)currentRoomPos.x + distBtwRooms,(int)currentRoomPos.y] != null) ||
                (nextRoom == 3 && spawnedRooms[(int)currentRoomPos.x,(int)currentRoomPos.y - distBtwRooms] != null) ||
                (nextRoom == 4 && spawnedRooms[(int)currentRoomPos.x - distBtwRooms,(int)currentRoomPos.y] != null))
            {
                nextRoom = Random.Range(1, 5);
            }
leaden ice
#

did you actually initialize the array?

craggy oyster
#

ofcourse i didnt forget to make the actual array

cloud python
simple egret
gusty monolith
craggy oyster
#

no

#

i thought u said it didnt need initializing

leaden ice
#

I never said that

craggy oyster
#

initializing would be a pain

leaden ice
#

why?

#

it's one line

#

spawnedRooms = new[width, height]

rigid island
craggy oyster
#

yea and its not really a total grid based game

#

i dont know where the rooms will be spawned

spring creek
gusty monolith
craggy oyster
#

it could go any direction

leaden ice
leaden ice
craggy oyster
#

yea

#

how would i calculate where to initialize if its procedural

leaden ice
#

You can use Dictionary<Vector2Int, ROom> instead

gusty monolith
#

your name? albert einstein.

leaden ice
#

or just HashSet<Vector2Int> if you only want occupancy

vagrant blade
#

@gusty monolith You can stop now, thanks

craggy oyster
#

dont get banned from the unity discord server man

#

youll regret it

craggy oyster
#

contains?

cloud python
#

I mean that have never happened before

spring creek
rapid stump
#

@leaden ice
Thank you for the help! Although I'm kind of stuck now... I think it's because of the size of the miniMap camera? Since the player is able to control the size. The bigger the orthographic camera is, the more inaccurate the localPoint is

leaden ice
#

like minimapCamera.TransformPoint(localPointFromClick)

cloud python
leaden ice
naive swallow
gusty monolith
#

<@&502884371011731486>

#

they wont leave me alone

naive swallow
#

Nah man mine's on topic

spring creek
naive swallow
#

Ah but I see the mods were already here, I was scroll locked. I'll stop resurrecting the past conversations

cloud python
simple egret
#

You need an email address, that's it.
No need to pay anything or belong to some company or organization

craggy oyster
#
            if((nextRoom == 1 && spawnedRooms.Contains(new Vector2Int((int)currentRoomPos.x + distBtwRooms, (int)currentRoomPos.y)) ) ||
                (nextRoom == 2 && spawnedRooms.Contains(new Vector2Int((int)currentRoomPos.x + distBtwRooms, (int)currentRoomPos.y)) ) ||
                (nextRoom == 3 && spawnedRooms.Contains(new Vector2Int((int)currentRoomPos.x + distBtwRooms, (int)currentRoomPos.y)) ) ||
                (nextRoom == 4 && spawnedRooms.Contains(new Vector2Int((int)currentRoomPos.x + distBtwRooms, (int)currentRoomPos.y)) ))
            {
                nextRoom = Random.Range(1, 5);
            }
#

ok how could i still be getting a null reference

#

im using a hashset

cloud python
naive swallow
leaden ice
craggy oyster
#

i just added the vectors to the hashset when i spawn them

leaden ice
#

you have to actually create the HashSet

naive swallow
craggy oyster
#
                roomPos =  new Vector2Int((int)currentRoomPos.x, (int)currentRoomPos.y + distBtwRooms);
                Instantiate(room, new Vector2(roomPos.x,roomPos.y), Quaternion.identity);
                spawnedRooms.Add(new Vector2Int(roomPos.x, roomPos.y));
leaden ice
#

so nowhere

#

you never did spawnedRooms = something

naive swallow
craggy oyster
#

yep

leaden ice
#

you never created the HashSet

#

you need to create it

craggy oyster
#

how does creation

#

HashSet<Vector2Int> spawnedRooms;

leaden ice
#

spawnedRooms = new();

#

HashSet<Vector2Int> spawnedRooms = new();

#

All you did was declare a variable

#

you didn't actually point your variable at an object.

craggy oyster
#

it works

#

but the logic doesnt

#

the code for checking if theres a room there i mean

#

could it be a rounding problem from my other vector2

#

should i use a vector2int for that

leaden ice
#

Yes you should be using Vector2Int all around

cloud python
#

because I am getting really panicked here

spring creek
cloud python
cloud python
spring creek
#

But also, consider git instead

rigid island
devout silo
#

I have a lightning shaped line for my game
I try to make it turn in the direction the player swiped
I have 2 vector3 variables that show the start and end position of the swipe
And I'm trying to get them to turn into an angle

#

!code

tawny elkBOT
spring creek
chilly surge
#

You can also use git completely locally without a remote origin, and you will still get all the benefits of being able to branch/revert/etc.

devout silo
#
                float angle = Vector3.Angle(end_t, start_t);

                transform.rotation = Quaternion.Euler(0, 0, angle);
leaden ice