#archived-code-general

1 messages Β· Page 95 of 1

knotty sun
#

he shouldn't need you to google that for him

wild pivot
#

no need to try and idk i guess sound so condescending. Im just confused as the unity docs for log files has no mention of the word build, built or builds

sour zealot
#

lemme see about the debuggin

dusk apex
#

||%USERPROFILE%\AppData\LocalLow\CompanyName\ProductName\Player.log||

wild pivot
#

not gonna question why that page says nothing about those logs being created for builds then

sour zealot
#

yeah just looked, the title menu is supposed to appear

#

and the loading menu is supposed to dissapear

#

which it does

wild pivot
#

oh ok, i guess that makes sense

#

still a bit weird they dont specifically say that it applies to built projects

dusk apex
#

There's the Editor, the Player and Unity Hub logs.

somber nacelle
dusk apex
#

All three and their specific locations were present in the above link.

#

Simply vocabulary, you'll get used to it.

knotty sun
grand compass
#

Hey all!
How could I add an offset to a spawned object (projectile in this case) in it's local X axis so that I can make something like the paint draw?
I have the offsets all figured out, but when I'm trying to Instantiate, then add +- offset to the projectile local X, it just doesn't work as in the drawing.
I'm passing a "Firing Point" Transform that is a child of the player.
Firing a single projectile works fine as it's just:

Instantiate(prefab, spawnPoint.position, spawnPoint.rotation);
#

PD: the projectiles spawn in the world without a parent.

wild pivot
#

Hi everyone I have a, what is to me, very odd issue.

Inside the unity editor i have an object which i move along the z axis, I then have a chain of 2 hinge joints on either side of another object to make it swing like paper when the target anchor of the top hinge joint is moved. I then get the anchor point to mirror the movement of the object.

In the first image attatched you can see the object which swings (the paper) and the object which moves (the holder on top). These work perfectly as intended in the editor.

And heres the hierarchy for them along with the script that moves the target anchors to mirror the position of the holder. https://hatebin.com/mjwfqjfjnn

all of this works as intended in the editor and there are no errors. When built the top target holder moves as expected, however the target with its hinge joint does not move at all. There are no errors in player.log

wild pivot
crystal vale
wild pivot
simple egret
crystal vale
#

If you add a float to the shader with the hinge joint, then add player prefs it should work πŸ˜‰

wild pivot
heady iris
#

This is word salad.

simple egret
#

Yeah no shaders here lol

wild pivot
#

do any of you know how id fix my issue?

simple egret
#

Nope sorry, issues like this where something works on one side but not on the other are the hardest to debug

wild pivot
#

yea im really confused by it, i couldve sworn this worked on my college computer when built so ima try that tomorrow. If that works then im at a complete loss.

My unity completely broke today somhow and i had to reinstall unity and visual studio so maybe its somhow linked to that? Idk im unsure

simple egret
#

You can try a full restart yeah, sometimes it's good to free up some RAM especially with Unity that'll get really slow after a couple of hours

bronze crystal
#

some tips to make my player stick to a sphere and rotate togheter while iam attached

wild pivot
#

make it a child of the sphere

bronze crystal
#

everytime when you collide with a object?

wild pivot
#

could also do something with hinge joints to pull it towards the sphere

simple egret
#

Also try renaming your script variables, maybe Unity picks up a change (or doesn't) which causes it to not be included in your build
You'll have to drag-drop references again into the Inspector

bronze crystal
#

and then on collision exit, deparent?

void basalt
#

If it works it works

wild pivot
void basalt
#

@bronze crystalYou're probably going to have issues parenting rigidbodies to other rigidbodies

#

just a warning

bronze crystal
#

ofcourse

void basalt
#

I think joints are meant for this stuff.

bronze crystal
#

you can imagine its more like a 3d player standing on a small planet

#

and this planet rotates

#

thats basically what i need

void basalt
#

If your planet isn't a rigidbody

#

then it might work out nicely

bronze crystal
#

yes my planet has no rigidbody

#

only my player

grave nebula
#

When should i use fixed update or regular update

void basalt
#

you'll probably want the unity answer if you're just starting out

#

@bronze crystalRemember that you'll also need to override gravity so that it's sucking towards the planet's center

#

if the planet isn't on 0,0,0 origin

#

also if you're trying to do a planetary-scale game, you're going to run into issues extremely quickly.

grand compass
wild pivot
heady iris
#

i'd slap together a new (equivalent) joint and see if that also breaks in the build

wild pivot
#

yea ill see if it builds on my college computer tomorrow, if not ill try making something similar in a diff project

grave nebula
void basalt
#

If you're accessing the physics engine, you use fixedupdate

#

The character controller does not use the internal physics system. It simply depenetrates itself out of collisions.

#

Could you use the physics engine API in update()? Probably. But the engine only ticks n times per second, so it really wouldn't make sense.

grave nebula
#

Physics engine entails what

void basalt
#

rigidbodies

#

and any other physics entities

#

joints, springs, etc

leaden ice
#

and, in fact the nature of the "player" in question

grave nebula
#

Oh i didn't know you could customize them via script

loud flume
#

So i had questions about this earlier and the person i talked to recommended a minimum spanning tree to path to the different rooms in the dungeon im making. I did that as shown in the first image but as you can probably also see its not pathing to all the rooms. The start and target points are unwalkable but i added something for that in the pathfinder. heres the part of the code that runs the pathfinder and generates hallways (https://paste.ofcode.org/3ZSDHyHZk73wHtAzUXAcSq)

leaden ice
#

what are the blue and green lines?

loud flume
# leaden ice these pictures are not clear

The first one is the dungon itself the green lines are the minimum spanning tree the blue are the hallways that were pathed. The shapes are the rooms the green square in the shapes are the doors. The second image is the walkable and unwalkable points the pathfinder uses (red being unwalkable)

leaden ice
#

The minimum spanning tree seems correct (although you seem to have drawn it offset from the map)
The rest of it would come down to how your "pathfinder" works and the spanning tree is definitely only creating paths between rooms it is not going to do anything with regard to the specific door locations or internal pathing of the rooms, etc..

loud flume
loud flume
compact spindle
#

I'm trying to add unique characters to a dictionary in a Manager Singleton script and it successfully adds them, but when I want to remove them, it's always a 50/50 on which get removed or if any successfully remove. I get errors telling me the Faction of the character (which serves as the key) does not exist in the dictionary.

Would anyone be able to tell me what's happening in this situation and how I could go about fixing it?

loud flume
leaden ice
tawny elkBOT
#
Posting code

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

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

compact spindle
#
    {
        if(character == null)
        {
            Debug.LogError("Character is null");
            return;
        }

        if(character.FactionName == null)
        {
            Debug.LogError("Faction Name is null");
            return;
        }

        if(character.ID == null)
        {
            Debug.LogError("ID is null");
            GenerateID(character);
            return;
        }

        if (!UniqueCharacterDictionary.ContainsKey(character.FactionName))
        {
            UniqueCharacterDictionary.Add(character.FactionName, new Dictionary<string, Character>());
            Debug.Log("Faction Name: " + character.FactionName + " added to dictionary");
        }

        UniqueCharacterDictionary[character.FactionName].Add(character.ID, character);

        Debug.Log("Character Added! " + character.ID + " Name: " + UniqueCharacterDictionary[character.FactionName][character.ID].name + " Faction: " + UniqueCharacterDictionary[character.FactionName][character.ID].FactionName);

        int characterAmount = 0;
        foreach (Dictionary<string, Character> faction in UniqueCharacterDictionary.Values)
        {
            foreach (Character c in faction.Values)
            {
                characterAmount++;
            }
        }

        Debug.Log("Character Dictionary Count: " + characterAmount);
        Debug.Log("Factions registered in Dictionary Count: " + UniqueCharacterDictionary.Keys.Count);
        // Debug.Log("Faction Name Keys: ");
        // foreach(var pair in UniqueCharacterDictionary)
        // {
        //     Debug.Log(pair.Key);
        // }
    } ```
leaden ice
#

triple ```

#

!cs

tawny elkBOT
#

You can format your multiline code block with C# highlighting! Just add cs to the start of it. Highlighting example below!

class Fluffs : FluffyCat
{
    public void PetCat ()
    {
        Debug.Log ("Petting Cat.")
    }
}
compact spindle
#

And here's my code to remove from the EntityManager Singleton:

```public void RemoveCharacterFromDictionary(Character character)
{
    if (!UniqueCharacterDictionary.ContainsKey(character.FactionName))
    {
        Debug.LogError("Faction with name: " + character.FactionName + " does not exist in the dictionary");
        return;
    }
    if (!UniqueCharacterDictionary[character.FactionName].ContainsKey(character.ID))
    {
        Debug.LogError("Character with ID: " + character.ID + " does not exist in the dictionary");
        return;
    }
    UniqueCharacterDictionary[character.FactionName].Remove(character.ID);
    Debug.Log("Character Removed! " + character.ID + " Faction: " + character.FactionName);
} ```
#

I got a lot of if statement checks and Debug.Log lines, but the actual lines to add and remove should hopefully be readable ^^

leaden ice
compact spindle
leaden ice
#

if not - that could lead to the error

compact spindle
#

I will in a future implementation (thanks for the advice! πŸ‘ ), but in this situation, I'm just spawning them in, adding them, and when the game is active, I hit the play button again to stop and on their OnDestroy calls, I remove them from the dictionary before destroying them. No change to any of their information after they've been added to the dictionary

#
        {
            if(!isPoolable) EntityManager.Instance.RemoveCharacterFromDictionary(this);
            Debug.Log(Name + " was " + "Destroyed" + " " + ID);
            Destroy(this.gameObject);
        }```
leaden ice
#

are you overriding those somewhere?

#

Might want to make sure you're calling base.Awake() in that case.

#

Maybe you never registered in Awake because you didn't call base.Awake in an override.

compact spindle
#

I called base.Awake() in my player and npc classes after initializing their data so that shouldn't be the cause--hmmm

#

Character.cs's Awake Method:

       {
           ResizableCapsuleColliderUtility = GetComponent<ResizableCapsuleColliderUtility>();

           Rigidbody = GetComponent<Rigidbody>();
           Rigidbody.useGravity = false;
           Rigidbody.constraints = RigidbodyConstraints.FreezeRotation;

           Timer = GetComponent<Timer>();

           if(!isPoolable) EntityManager.Instance.AddCharacterToDictionary(this);
       } ```
#

NPC.cs's Awake Method that overrides Character.cs's Awake:

    ```protected override void Awake()
    {
        this.Animator = GetComponent<Animator>();
        this.NavmeshAgent = GetComponent<NavMeshAgent>();

        this.NPCAnimationData.Initialize();

        this.Name = this.NPCData.Name ?? "NPC";
        this.ID = this.NPCData.ID;
        this.FactionName = this.NPCData.FactionName;

        this.NPCMovementStateMachine = new NPCMovementStateMachine(this);

        base.Awake();
    }```
leaden ice
compact spindle
#

Not that I can see from the console:

leaden ice
#

you'd have to scroll up

#

oh i see

compact spindle
leaden ice
compact spindle
#

I only have one instance of my Entity Manager running and the Singleton<T> class it's inheriting has a case in its Awake method that Destroys any preexisting instances so hopefully it's pointing to the correct Instance's dictionary

loud flume
lunar forum
#

Is there a component that's different from a collider that can detect if something is touching or in it? I ask because I also need a collider for detecting... well... collisions. I can't conceptually understand how to distinguish between two colliders when you can't name them or tag them differently.

void basalt
#

built into the standard collider

leaden ice
#

Put them on separate child objects

void basalt
#

Sorry, didn't read the entire question. Another solution would be to use collider instance IDs as dictionary keys if you want a direct lookup to something.

#

You actually probably want to have the collider itself as the key

solid rampart
#

Ty

wise kindle
#

I'm trying to make a script for picking up an object (but all it does is make the flashlight disappear from the game), and when I press E, nothing happens. I'm assuming it's cause of how I'm referencing the object I'm trying to pick up. What would you guys suggest?

public class Pickup : MonoBehaviour
{
    GameObject PickupObject;
    public bool pickedup;
    public float maxDistance = 2;
    public float speed = 1;
    public enum axis { X = 0, Y = 1, Z = 2 }
    public string keyToPress = "e";

    public CrosshairCanvas crosshairScript;
    private AudioSource sound;
    private float r;
    private bool pickingup;

    private Ray ray;
    private RaycastHit hit;
    private bool crosshairChange;

    void Start()
    {
        r = 0;
        sound = GetComponent<AudioSource>();
    }

    void Update()
    {
        ray = Camera.main.ViewportPointToRay(new Vector3(0.5F, 0.5F, 0));
        r += Time.deltaTime * speed;
        if (Physics.Raycast(ray, out hit, maxDistance) && hit.transform == this.transform) {
            if (Input.GetKeyDown(keyToPress) && pickedup == false) {
                
                this.PickupObject.SetActive(false);
                r = 0;
                if (sound.clip != null) {
                    sound.Play();
                }
            }
            if (crosshairScript != null) {
                if (crosshairChange == false) {
                    crosshairChange = true;
                    crosshairScript.interactable = true;
                }
            }
        }
    }
}
potent sleet
leaden ice
#

I think the script goes on the object to be picked up

nova magnet
#

guys do you know how to make a shotgun in unity

potent sleet
#

ah that's different

leaden ice
#

Very unclear what PickupObject is though

leaden ice
nova magnet
potent sleet
#

yea why not

leaden ice
#

Depends how you want the shotgun to work

#

You could use Raycasts, projectiles

#

Whatever you want

nova magnet
empty token
#

I'm having some issues which are half code half not. I'm just using a simple script to move a UI image from off screen onto the screen. The code is in here:
https://paste.ofcode.org/BH5WQTj3WYNJpJQsfjvypD

As you can see, my problem is two things: The image/object moves into a different position depending on the resolution. The objects are anchored to the bottom of the screen. I accidentally programmed my game in 800x600 or whatever it was resolution in the Canvas, however I've set the camera and project settings to use fullscreen resolutions which would be 1920x1080 as default so I'm a bit stumped on this. Another issue, a bit harder to see, is that the images are glitching out and changing sizes as they move upwards. I'm not sure what's causing that. Could I get some help?

hazy tinsel
#

Id like to programatically toggle "use reference" for the left hand and right hand turn actions, but can't figure out how to do this by script. any help please?

gloomy mortar
#

is there a way to reference a scene in a script? I tried SceneAsset and Scene from the SceneManagement, but both cannot be set via the drag and drop parameters.

#

nvm. Its scene asset it seems. The drag and drop just doesnt work... need to select it from a list.

hazy tinsel
#

if worst comes to worse, i could just dereference the entire action, but I was looking for a cleaner answer

hazy tinsel
#
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.XR.Interaction.Toolkit;
using UnityEngine.SceneManagement;

public class Controls : MonoBehaviour
{
    private static Controls _instance;
    public static Controls Instance { get { return _instance; } }

    [SerializeField] private ActionBasedSnapTurnProvider SnapTurnProvider;
    [SerializeField] private ActionBasedContinuousTurnProvider ContinuousTurnProvider;
    [SerializeField] private ActionBasedContinuousMoveProvider ContinuousMoveProvider;

    [SerializeField] private GameObject RightRayInteractorObject, LeftRayInteractorObject;
    private GameObject RayInteractObject;

    [SerializeField] private InputActionReference m_RightSettingsAction, m_LeftSettingsAction;
    private InputActionReference m_SettingsAction;


    public bool LeftHandedModeEnable = false;
    private bool RayInteractorEnableState = false;

    private void Awake()
    {
        if (_instance != null && _instance != this)
        {
            Destroy(this.gameObject);
        }
        _instance = this;

        SnapTurnProvider.enabled = false;

    }

    private void FixedUpdate()
    {
        m_SettingsAction.action.performed += SettingsButtonPressed;
    }

    public void LeftHandModeEnabled()
    {
        RayInteractObject = LeftRayInteractorObject;
        m_SettingsAction = m_LeftSettingsAction;
        SnapTurnProvider.leftHandSnapTurnAction.// what goes here?
    
    }

    public void RightHandModeEnabled()
    {
        RayInteractObject = RightRayInteractorObject;
        m_SettingsAction = m_RightSettingsAction;
    }

    public void SettingsButtonPressed(InputAction.CallbackContext obj)
    {
        RayInteractorEnableState = !RayInteractorEnableState;
        RayInteractObject.SetActive(RayInteractorEnableState);
    }
    
}

hazy tinsel
#

what do you mean?

potent sleet
hazy tinsel
#

... Im not sure what im trying to access, i guess thats the question

potent sleet
#

ok so what do you need to do ?

hazy tinsel
#

i want to toggle the "use reference" button by script

#

it works perfectly via the inspector window

#

but not sure how to via script

potent sleet
#

so then why don't you show that script

hazy tinsel
#

I'm not a unity beginner, i just dont have experience with the new input system

#

this "use reference" button pops up in inspector when Serializing any "InputActionReference"

potent sleet
#

which button?

#

I see a boolean toggle

hazy tinsel
gloomy mortar
#

OK... I have something weird. There is SceneAsset (which allows drag and drop/selection of a scene) and I have Scene, but Scene supports the SceneManager, which is used to get active scene. Anybody know how you can get Scene to become drag and droppable?

potent sleet
#

that's a checkbox

hazy tinsel
#

okay, a boolean toggle. sorry i wasn't using the correct nomenclature

potent sleet
#

or maybe in a struct or something, no clue. I haven't seen the script.

#

I don't use XR

potent sleet
#

hella dirty but you might be able to use Object

gloomy mortar
hazy tinsel
gloomy mortar
potent sleet
gloomy mortar
#

not even the loadscene function takes a scene object or scene asset object. Its weird

gloomy mortar
potent sleet
#

that's prob smarter

potent sleet
gloomy mortar
hazy tinsel
#

do you happen to know about that struct?

potent sleet
#

never seen it

hazy tinsel
#

ok

nova magnet
#

how do i change the angle of raycasts?

hazy tinsel
potent sleet
gloomy mortar
#

Finally, my combat system works πŸ˜„ easily able to enter battle and exit while retaining the scene you were prior in. Even with the possibility to set a new scene for after combat.

potent sleet
gloomy mortar
#

atleast the entering and exiting the battle works xD

calm heath
#

how would I make a point system so that when my ball touches a line then i get points
and then display the points on the top right screen?

potent sleet
vernal wren
#

Hi guys, yesterday I downloaded Vector Graphics bcs I want to work with .svg assets. Problem is that I am building WebGL version. When I build it manually .svg works, but when I am build it via command line for some reason .svg stop working πŸ˜„ I am using 2021+ version, latest version on Vector Graphics, WebGL 2 only. Any idea where can be problem?

abstract timber
#

hey there i am not the best at math but how whould i put i distance field in this code i cant really seem to find a soloution. The image kinda explains what i am trying to do

        t += Time.deltaTime;
        if (target != null && t <= 1)
            transform.position = Vector3.Lerp(transform.position, new Vector3(target.position.x - distance,
                transform.position.y, target.position.z - distance), t);
hard estuary
ruby fulcrum
#

if i have a bunch of colliders in a rig whats the best way to receive collision events from them

ruby fulcrum
abstract timber
#

like in the photo

cursive moth
cursive moth
abstract timber
#

i would like some sort of an offset

#

but what i am doing now makes it stuck at the left corner

#

if you like on the photo i would like it to move towards the capsule but stop before it goes into it

cursive moth
abstract timber
#

yes

#

but i would like to manually change the distance

cursive moth
#

if yes, are you sure that lerping is what you want here?
can said objects move or are they static?

abstract timber
#

the cube would be able to move

#

and the capsule should be static

cursive moth
#

ok, lerping should suit your needs then ig

#

for lerping the position you need 2 Vector3.
Your first Vector3 should be = cube's transform.position
Second one should be target's transform.position with + offset that you would like to apply
Then just lerp between the two said vectors using Vector3.Lerp()

#

sk the code you sent above has 2 issues that I can see, first, you need to store the starting position before the while loop, you can't use the updated value

#

2nd, you shouldn't do - distance, if the distance was (-3, 5, 8) it would do +3, -5, -8
What you want to do is + that distance instead

abstract timber
#

the photo hasnt really anything to do with the code

#

it was just to show how i whould want it the numbers there really doesnt matter

#
    [SerializeField] private Transform target;

    [SerializeField] private float t = 0;
    [SerializeField] private float offset = 1;

    private void Update()
    {
        t += Time.deltaTime;

        if (target != null && t <= 1)
            transform.position = Vector3.Lerp(transform.position, new Vector3(target.position.x + offset,
                transform.position.y, target.position.z + offset), t);
    }
#

this is the full code

#

it makes it go to a specific place

cursive moth
#

well if you want numbers that way you should probably do what I just recommended, other approaches are sure possible but I might not be able to help with some

cursive moth
abstract timber
#

yes but that still doesnt accomplish what I'm trying

#

one sec

cursive moth
#

although, I would highly recommend using a coroutine for this, not entirely sure how you'll achieve this in Update

abstract timber
#

in the player script i use a coroutine

abstract timber
cursive moth
#

so why not send that code instead, what you sent should work from what I can tell

abstract timber
#

right now i get the same point every time

#

look at the video

#

the cube goes the same place every time

#

it should go where the dots are on the new photo

cursive moth
#

that means your target position is not updating

abstract timber
#

what

#

no

#

i said it was static

#

The player should move towards the target and stop in front of it

#

how whould i make it do that

cursive moth
#

so, you have a single target with multiple distances?

cursive moth
#

could you please send the actual code this time so that we can try and figure out what's wrong

abstract timber
#

thats the cude for the cube and the capsule

cursive moth
#

you said that's an example code

abstract timber
#

the black sphere is where the cube is gonna move

cursive moth
#

and that you are using a coroutine

abstract timber
#

the cube and the sphere is a part of the example

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

public class MoveTowards : MonoBehaviour
{
    [SerializeField] private Transform target;

    [SerializeField] private float t = 0;
    [SerializeField] private float offset = 1;

    private Vector3 startingPos;

    private void Start()
    {
        startingPos = transform.position;
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.black;
        Gizmos.DrawSphere(new Vector3(target.position.x + offset,
                transform.position.y, target.position.z + offset), .6f);
    }

    private void Update()
    {
        if (Keyboard.current.spaceKey.wasPressedThisFrame)
        {
            startingPos = transform.position;
            t = 0;
        }

        t += Time.deltaTime;

        if (target != null && t <= 1)
            transform.position = Vector3.Lerp(startingPos, new Vector3(target.position.x + offset,
                transform.position.y, target.position.z + offset), t);
    }
}

cursive moth
#

well I already told you why this wouldn't work

abstract timber
#

thats the entire code

#

this code returns the same position each time

cursive moth
#

ok this one is different, let me take a look

abstract timber
#

yes i changed it a bit while we talked

abstract timber
# abstract timber

but as you can see here the gizmo does not move in front of the cube it just stands

cursive moth
bronze crystal
#

i Want my player, little sphere to stick on the bigger sphere anywhere and move if the bigger sphere would move towards adirection. someone can help with that? ```private void FixedUpdate()
{
if (isSticking)
{
playerRigidbody.transform.position = gameObject.transform.position;
Debug.Log("sticky sticky");

    }
    else
    {
        // Enable the player's rigidbody gravity
        playerRigidbody.useGravity = true;
    }
}```
abstract timber
#

im no the best explainer

tardy mortar
#

Good morning.
Let's say I have a class A. And I have a scriptable object that was a list of class A. I will inherit this class A on to another classes.

In another class, how could I, from that list of class A, pass a parameter that would be the type of the classes that I inherit from, so that I can use methods from that class?

I don't know if I'm making myself clear or if it's possible :')

cursive moth
abstract timber
#

okay

#

this is what i want

#

for the cube to move towards the target with an offset (the dot)

#

how whould i do that

cursive moth
#

ok, and what's happening?

abstract timber
#

this is the code right now for the dot

#
    private void OnDrawGizmos()
    {
        Gizmos.color = Color.black;
        Gizmos.DrawSphere(new Vector3(target.position.x, transform.position.y, target.position.z), .6f);
    }
cursive moth
#

by using the Vector3.Lerp() between the starting and a target pos + offset

abstract timber
#

it just apeers inside the target

cursive moth
#

because that is what you are doing

abstract timber
abstract timber
#

thats why im asking how whould

#

i

#

add an offset

#

and the sphere is at the path of the player

cursive moth
#

so, the problem is that you want to add an offset so that it's offset towards a player for the same distance no.matter which side the player is on?

abstract timber
#

yes the offset should be at same distance

abstract timber
cursive moth
#

so you need to move it towards the player if I understand that correctly

abstract timber
#

no the player should move to the sphere / dot's position

#

but i cant figure out how to get the right position of the dot

cursive moth
#

exactly what I was asking, you need to offset the dot towards a player

abstract timber
#

yes

#

yes

#

i just dont know how

frozen hemlock
#

I am looking for the right way to do Click and Drag a Physics Object over a Floor with Walls on it. This is my setup right now. The problem is that if I drag my mouse trough the wall the Physics object will be dragged trough the wall too. But it should stop there as it should not be able to pass trough the wall.
This is a screen recording of it. And a screenshot of my visual script.

cursive moth
#

ok, you need a Vector3.Distance(startingPos, targetPos).normal * distance

abstract timber
#

like where whould i put the result of vector3.distance

cursive moth
#

a normal is basically the normal of that distance which is how you get where the player is lets say rotation wise looking from the target, then you multiply that by the offset from the target(you called it distance) and that should do it

cursive moth
#

just use your var names and Vector3 instead of V3

#

gtg, be back a bit later, if you have any questions feel free to @ me and I'll reply as soon as possible

abstract timber
#

@cursive moth sorry

#

but

#
        float distance = Vector3.Distance(startingPos, target.position) * offset;
        Gizmos.DrawSphere(new Vector3(target.position.x + distance, transform.position.y, target.position.z + distance), .6f);
#

am i doing something wrong?

cursive moth
abstract timber
#

ohh

#

well it is kinda

#

right

cursive moth
#
Vector3 drawPosition = target.position + Vector3.Distance(target.position, startingPos).normal * offset;
Gizmos.DrawSphere(drawPosition, .6f);
hexed pecan
#

That does not compile though

#

What is float.normal?

abstract timber
#

you cant normalize a float

#

i dont thimk

#

think

cursive moth
#

he needs vsctor3.Normal() instead iirc, I've had an hour of sleep and this was my fault

hexed pecan
#

Did you mean (target.position - stattingPos).normalized or something?

cursive moth
#

yeah thag would work ig

hexed pecan
#

I didnt see what this is for though, lemme read

cursive moth
#

yeah that's what he needed I messed up

abstract timber
#

i cant normalize a float

cursive moth
#

do what osmal said, get the - of the 2 vectors and normalize it

#

by normalize it I mean get a .normalized property

abstract timber
#

like this?```
Vector3 drawPosition = target.position + (target.position - startingPos).normalized * offset;
Gizmos.DrawSphere(drawPosition, .6f);

cursive moth
#

yeah, I think that should work

abstract timber
#

yeah it does thanks

outer plinth
abstract timber
#

yeah it does work thanks

cursive moth
outer plinth
#

@cursive moth I just figured there might be an easier way apart from creating a method which accepts the enum, are there any other ways or am I just being stupid?

cursive moth
outer plinth
#

ty sexy

orchid bane
#

How can I reimport whole project?

hexed pecan
#

Right click the project browser and Reimport All

#

Or delete your Library folder and relaunch

ember ore
#

I have this script :

    public class CameraFacingBillboard : MonoBehaviour
    {
        private Camera _camera;

        private void Awake()
        {
            _camera = Camera.main;
        }
        
        private void LateUpdate()
        {
            var cameraRotation = _camera.transform.rotation;
            transform.LookAt(transform.position + cameraRotation * Vector3.forward,cameraRotation * Vector3.up);
        }
    }

But when i attach it to an object, it never looks at the camera. Why`?

leaden ice
#

This code seems to be trying to make it look in the same direction the camera is looking

#

(in a pretty convoluted way)

ember ore
#

Alright thanks, that works! πŸ˜„

#

Well kinda, it looks at the camera with its back for some reaon

#

reason

hexed pecan
#

Sounds like your model is flipped

ember ore
#

Is it? I mean... its all zeroed

leaden ice
#

That's just how text works

#

The "back" is where it's readable from

ember ore
#

Oh i see... So i should just rotate it by 180 degrees i guess

leaden ice
#

No

#

transform.rotation = Quaternion.LookRotation(transform.position - _camera.position);

ember ore
scarlet nimbus
#

Hi, I am starting to learn DOTS, imported entities package but I get this error:
Any idea why? When I inherit from the IComponentData interface, for example, I don't get any errors.

bronze crystal
#

anyone can helpo

late lion
neon plank
#

How can I pass a T[] as NativeArray<T> in a job?
I'm trying:

GCHandle handle = GCHandle.Alloc(array, GCHandleType.Pinned);
NativeArray<float3> native = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<float3>((void*)velocitiesHandle.AddrOfPinnedObject(), count, Allocator.Invalid);
new MyJob { Velocities = native }.ScheduleParallel(query, default).Complete();

But I get:

InvalidOperationException: The UNKNOWN_OBJECT_TYPE IntegrateJob.JobData.Velocities has not been assigned or constructed. All containers must be valid when scheduling a job.

I would like to avoid having to copy the content into the native array, and I can't avoid the managed array since I get it from an API outside my control.

late lion
neon plank
#

Ok

#

Thanks

woeful spire
leaden ice
#

That's what would happen

#

If you had it the other way

woeful spire
#

oh right, I've pretty much only used world UI - that didn't even cross my mind hahah.

#

thanks, that makes very much sense.

regal epoch
#

I have some weird stuff going on in my code. I'm makeing a simple Higher Lower card game, but the card pictures are updating one round too late? at the start of every round, a new card number gets randomly chosen. after i click a button an animation starts playing and the card turns around etc. The number updates every round, that is working. The thing is that the picture on the card has a delay of 1 round. So the first round it's just a white sprite, but then the second round it has the picture of the card of the first round. and then the third round the second picture etc. Even though the picture replace is right under the number replace, it just completely skips that part and does it the round after. been banging my head for 3h now please someone help.

#
    {
        textDisplayNewCard.SetActive(false);
        string roundName = names[nameIndex];
        textDisplayName.GetComponent<Text>().text = roundName;

        do          //get a new random number
        {
            NewCard = Random.Range(2, 11);
        } while (NewCard == OldCard);       //repeats when newNumber == oldNumber
        
        Debug.Log(NewCard);
        Debug.Log("heart" + NewCard);
        NewPlayingCard.sprite = someOtherSprite2;       //replaces card with the new card
        someOtherSprite2 = Resources.Load<Sprite>("PlayingCards/heart" + NewCard);
        Debug.Log(Resources.Load<Sprite>("PlayingCards/heart" + NewCard));


        OldPlayingCard.sprite = someOtherSprite;        //replaces the old card with the new card
        someOtherSprite = Resources.Load<Sprite>("PlayingCards/heart" + NewCard);


        string stringrandomCard = NewCard.ToString();   //displays the random newNumber for reference
        textDisplayNewCard.GetComponent<Text>().text = stringrandomCard;



        nameIndex++;        //cycles through the playerList
        if (nameIndex == names.Length)
        {
            nameIndex = 0;
        }
        roundIndex++;

        if (roundIndex > numberOfRounds)        //ends the game after numberOfRounds has been reached
        {
            EndScreen();
        }
    }```
#

the code is a bit messy i know still working on that

#

oh i found the problem. Basically, because the image is inactive it doesn't update untill its active, which is all the way at the end of the animation. Then it goes back to inactive. So it updates every time at the end of the animation, which is why then the picture is always 1 round behind

bright relic
static matrix
#
  const int rotLen = 4;
        int* rots = stackalloc int[rotLen]; 
        rots[0] = 0;
        rots[1] = 90;
        rots[2] = -90;
        rots[3] = 180;
        
        //Place the Layout
        Layout = Instantiate(Struct, transform.position, Quaternion.identity);
        //Randomize The Layout's Rotation
        Layout.transform.eulerAngles = new Vector3(0, rots[Random.Range(0, 4)], 0);

Is this a good use of stackalloc, or will my unity implode

dusk apex
#

Was it necessary? Looks like unsafe coding with pointers and whatnot.

static matrix
#

I mean I'm trying to make my game run faster, and stackalloc seemed like a way to do that

#

although its mostly on graphics that are hurting performance

dusk apex
#

Use the profiler.

static matrix
# dusk apex Use the profiler.

I have my guy
although Im going to take another look
there isn't anything obvious bringing it down to 35 fps but maybe there is and im just missing it

late lion
static matrix
#

ooh what does span do
will it enfastenate my code

late lion
#

Span<int> rots = stackalloc int[rotLen];

static matrix
#

let me try that and see if my code explodes

late lion
#

It's an abstraction to make pointers safer, but performance should be basically the same when it compiles.

dusk apex
static matrix
late lion
dusk apex
#

This sounds like it's going down a bad rabbit hole.

static matrix
#

2021

late lion
#

2021.3?

static matrix
#

.1

late lion
static matrix
#

let me look at the profiler again

static matrix
dusk apex
#

If you're doing cs private void Update() { //Other stuff that doesn't matter Instantiate(...); }your computer is going to be destroyed.

static matrix
#

oh its not in update dw

#

im not stupid enough to instantiate in update

dusk apex
#

Look at the profiler. Then later consider pooling if you're intensively instantiating/destroying objects else .. just look at the profiler.

late lion
#

So are you trying to optimize the load time?

static matrix
#

im trying to optimize the fact it runs at 35 fps

opal cargo
#

Hey guys, trying to write my own Rigidbody Character Controller but getting stuck on something that should be straight forward, at least in my mind πŸ˜„
Want to let my Rigidbody float over ground by snapDistance but I'm always on ground and sometimes not getting any hits at all

private void setGravity(bool status) => _rb.useGravity = status;
private void checkGround()
{
    Vector3 pos = transform.rotation * transform.position;    
    // Check for ground by shooting ray from position downwards
    _onGround = Physics.Raycast(pos, Vector3.down, out _groundHit, _groundCheckDistance,~LayerMask.GetMask("Player"),QueryTriggerInteraction.Ignore);

    if(_onGround)
    {
        setGravity(false);
    }
    else
    {
        setGravity(true);
    }
}

private void snapToGround()
{
    if(!_onGround)
        return;
    if(_groundHit.distance > 0)
    {   
        Vector3 newPos = transform.rotation * transform.position + Vector3.down * (_groundHit.distance - _snapDistance);
        _rb.MovePosition(newPos);
    }
}

void Update(){
    checkGround();
}

void FixedUpdate(){
    snapToGround();
}
late lion
static matrix
#

I mean i am calling it a lot
and it isn't consistent
it swings wildly depending on where im looking

late lion
#

Have you seen that this function takes a significant time in the profiler?

heady iris
#

use the profiler or you're wasting your time

dusk apex
static matrix
#

no, mostly in the profiler it's Camera.Render
Im looking at it right now

heady iris
#

if your performance varies wildly depending on where you're looking, then i'd guess you have some expensive renderers

#

high-poly meshes, perhaps

static matrix
#

I messed up the layout augh holdon let me get it back

heady iris
#

or very expensive materials (that'd be something you'd know you did, though)

static matrix
#

this bit seems to be the slowing one

#

Which is weird bcause the game is like 90% cubes

dusk apex
#

You may need to show more the the profiler.

static matrix
#

yeah lol

#

one mo

late lion
#

That's showing the CPU rendering time, which is all about culling, batching and draw calls. Shader or mesh complexity will not affect the CPU time.

static matrix
#

here are some things

#

ok well
it seems like its causing 10 ms of lag which seems bad

#

idk

opal cargo
static matrix
#

is there just something im missing

heady iris
#

perhaps you can show us these stats

static matrix
#

I mean the drawing bit seems the most expensive

heady iris
#

also lol 1000 fps

opal cargo
#

Thought Unitys physics engine would prevent this but meh

static matrix
dusk apex
static matrix
heady iris
#

hmm, 819,000 triangles

#

not great, not terrible

static matrix
#

why are there 81900 triangles its just cubes

dusk apex
#

For cubes?

opal cargo
heady iris
#

perhaps you have some very hi-poly cubes

static matrix
dusk apex
static matrix
#

1.1m for what appears to just be cubes

heady iris
#

well, that appears to just be The Backrooms

#

is the level one giant mesh?

#

or is each wall segment its own model?

static matrix
#

each wall segment is its own object

heady iris
#

inspect one of these wall segments

#

i.e. click on it in the scene view

static matrix
#

ok

heady iris
#

then, click on the "mesh" field of the Mesh Filter

opal cargo
# dusk apex I'm not sure what you're asking then.

Wonder if my approach is even the right one, calculating distance between my object and ground, deactivating gravity and setting my Y-Position with an offset to the ground.
Since it doesn't work means I'm doing it wrong πŸ˜„

static matrix
heady iris
#

Cube (Mesh Filter)

#

up top

#

that should highlight the mesh in the project view

#

wait, that does not do what i wanted

static matrix
#

one mo my layout is wierd for the profiler

heady iris
#

i want to look at the mesh asset itself

dusk apex
heady iris
#

it looks like imported meshes will get highlighted in the project pane, at least

static matrix
#

yeah the cube mesh is just the basic unity cube

heady iris
#

perhaps you are instantiating many many many copies of the wall segment by mistake?

#

or maybe the wall segment is very small

opal cargo
static matrix
#

it might be materials

#

the walls are slightly emissive

#

let me turn that off

heady iris
#

no, we're very interested in the 819,000 triangles right now

static matrix
#

ok

dusk apex
# opal cargo So not using RBs gravity for that?

I was under the impression that you weren't using rigidbody physics and were creating your own physics. If with rb, you'd just use rb and hackish workarounds with disabled/kinematic physics and whatnot.

static matrix
#

here one sec

opal cargo
dusk apex
#

It's a tough fight regardless as rb simulates physics using a rigid body whereas we're more likely to want "game/fake physics"

#

There are a lot of tutorials out there on kinematic rigid bodies and a few assets that have been recommended here before.

ember ore
#

mode.Rotation is a Vector3 like this : 90,90,90.
After ther localEulerRotation assignment the eulerAngle is just 90 instead of 90,90,90... why?

#

What have i missed?

opal cargo
ember ore
#
var angle = new Vector3(90,90,90);
deviceRoot.transform.localEulerAngles = angle;

// deviceRoot.transform.localEulerAngles is just (90,0,0).

Why is that?

late lion
ember ore
#

Ah i see... how can i "force" it to use (90,90,90) instead?

#

Without that conversion*

uncut palm
#

Does anyone have any idea why objects that are Instantiated do not act the same as ones that are dragged into the scene? I have a basic little AI system, but I’m not using any NavMeshes or anything. No variables are plugged into the scene, the AI should be completely standalone (but only works when dragged into the scene). Any ideas?

late lion
#

You could save the Euler angles in your own variable if you want to retrieve it again unmodified.

#

But there are very few reasons to prefer Euler angles over Quaternion.

ember ore
# late lion You can't. Unity uses `Quaternion` to represent 3D rotation. It shows Euler angl...

I hate rotation stuff... dammit
E.g. i have a user defined format (json) where the user can set the objects rotation in euler.
And the euler rotation is 90,90,90.

Now when i assign it to the object, the euler rotation in the editor shows 90,0,0 and is therefore invalid.
I basically wanna take the euler anlge from the object, put it into json and load it back... i mean it cant be that hard or?

hexed pecan
#

Generally your character and the obstacle would both have a collider

#

What kind of a game is it, 2D or 3D, how are you moving your character etc

late lion
# ember ore I hate rotation stuff... dammit E.g. i have a user defined format (json) where ...

Unity just doesn't save the Euler angles, so there are no angles to retrieve. You can only calculate them from the Quaternion, but since there are multiple Euler angles that can represent the same rotation, you can't get them all.

But just because Unity doesn't keep track of it, it doesn't mean you can't. When you load the object, you can keep the original Euler angles somewhere other than in its Transform and read it back when you want to serialize it back to JSON. Just don't expect the numbers to stay the same if you then use Unity functions to rotate the object, since that will be using Quaternion.

hexed pecan
#

If that's the one that controls the step height, not sure

#

Try it out

ember ore
# late lion Unity just doesn't save the Euler angles, so there are no angles to retrieve. Yo...

What i just dont get is... i mean i have a euler of 90,90,90.
I set the euler for a gameobject to exact those values : transform.eulerAngles = new vector3(90,90,90)
They are converted to quternion...

And suddenly the inspector of that gameobject shows me euler of 90,0,0.
Hows that even possible? I mean, even if the euler are converted to quaternion and back, they should stay the same right?

ashen yoke
#

inspector doesnt show the actual euler, and the actual euler will convert your invalid provided v3 to a valid one

ember ore
#

Oh it does not? What exactly does the inspector show then?

ashen yoke
#

"relative" offset from the quaternion identity

#

also its local

ember ore
#

So wait a sec

ashen yoke
#

are you aware of gimbal lock?

ember ore
#

So that V3 is the offset basically?
What do i need to do in order to set the rotation to get exact those values above (90,90,90) to show up in the inspector programatically?

ashen yoke
#

example, you rotate an object by -720 on x, inspector shows -720, but the euler stores only values 0-360

ember ore
#

Since i want that the user basically just takes those values from inspector, put them into json, app is loading that json and boom the inspector shows those exact values

late lion
ashen yoke
#

so what inspector does is it compares its quaternion rotation, which results in a single -720 rotation, to the objects indentity or zero rotation quaternion and displays to you -720

late lion
#

A more extreme example is for example the rotation 360, 0, 0. Obviously, it's the same as 0, 0, 0, because it's just a 360 around the X axis. Quaternion doesn't have this problem, so when you convert Euler to Quaternion, that problem disappears.

ashen yoke
#

euler values will not give you -720, it just cant and its not how it works

#

its inspector being human friendly and confusing programmers

ember ore
#

Okay but then how do I reach my goal?
I want to set the rotation of an object so that its inspector shows exactly the V3 of 90,90,90.

In the json I would then store 90,90,90, the app loads this and sets the rotation of the object so that its inspector shows 90,90,90. How would this work?

ashen yoke
#

what you can do is to convert both 90,90,90 and 90,0,0 to quaternions and compare them, if they are equal this means rotations are equal, and it doesnt matter what inspector is showing

late lion
#

If you look inside a prefab or scene file, you'll see how Unity saves the Transform values:

Transform:
  m_ObjectHideFlags: 0
  m_CorrespondingSourceObject: {fileID: 0}
  m_PrefabInstance: {fileID: 0}
  m_PrefabAsset: {fileID: 0}
  m_GameObject: {fileID: 8216044101241921426}
  m_LocalRotation: {x: 0.70710677, y: 0, z: 0, w: 0.70710677} # This is the true Quaternion rotation.
  m_LocalPosition: {x: -1.0077429, y: 0.19608417, z: 2.4774108}
  m_LocalScale: {x: 1, y: 1, z: 1}
  m_ConstrainProportionsScale: 0
  m_Children: []
  m_Father: {fileID: 0}
  m_RootOrder: 0
  m_LocalEulerAnglesHint: {x: 90, y: 90, z: 90} # This is what you see
--- !u!33 &2518793210753473943
ashen yoke
#

"hint"

late lion
#

If this is purely for the editor, you can use the SerializedProperty API to set the m_LocalEulerAnglesHint property.

ember ore
late lion
#

It would look something like this:

var obj = new SerializedObject(transform);
SerializedProperty localEulerHintProperty = obj.FindProperty("m_LocalEulerAnglesHint");
localEulerHintProperty.vector3Value = theJsonRotation;
#

There is no way to get the inspector to show the rotation 90, 90, 90 without setting this internal property.

#

Though there may be some nicer editor API to change this that I'm not aware of.

ashen yoke
#

im pretty sure that will be the case

#

then just ignore the inspector values

ember ore
#

No, I don't want to change the inspector value directly. I want to store 90,90,90 as euler hint in a json and assign it as rotation to an object that if I would look at the inspector.... I would also see 90,90,90 in it.

#

Oh god, i will never touch rotations again. My brain is just not capable of those

ashen yoke
#

it will grow on you

late lion
hushed needle
#

If instead of using vector 2 in a two dimensional game, I use x and y of vector 3, will there be a problem?

ember ore
#

User puts 90,90,90 in a file as a readable human euler angle

ashen yoke
#

yes and

late lion
#

The SerializedProperty method is the only way to do this.

ember ore
#

I wanna convert that to a rotation and assign it to a object. So when i would look into the unity inspector it would also show me the same hint

heady iris
#

Vector3 can convert to Vector2 by dropping the Z coordinate

#

you'll only have problems if you try to, say, add a vec2 and a vec3

#

c# won't know what to do

#

so you'll have to explicitly convert one

late lion
ember ore
hushed needle
#

The only reason I wanted to use V3 instead of V2 is because I can't subtract a value with V2

#

Or is there a way?

heady iris
#

if you use Vector3.right, the subtraction will work

#

and then the result will be converted to a vector2

hushed needle
#

oh

orchid bane
#

How do I place red text like on this screenshot? So that it doesn't rotate and doesn't get smaller on sides because of perspective

hushed cloud
#

does anyone have some advice for working with slerp, i have a ui setup so that when you press a button, it uses slerp to move all the ui to a point ive defined, which does work, but its moving in a parabola rather than in a straight line but i cannot figure out the reason for it

#

this is what i have for the code

heady iris
#

slerp is not for a linear movement!

#

use Lerp

#

"Slerp" means "Spherical lerp"

#

imagine putting a sticker on a ball, and then rotating the ball

#

that's the path a slerp produces

hushed cloud
#

ohmygosh yeah that makes a lot of sense, tysm!

heady iris
#

slerp is great for camera movements

heady iris
#

is there a nice way to reference a specific material slot on a renderer? I want to set a material property block for just one slot

#

i guess i could assign a reference to the material and then compare it to the sharedMaterials array of the renderer

celest sable
#

Does anyone know resources or general tips for how to implement a drifting mechanics on a car without using a rigidbody?

heady iris
#

i guess i would limit how quickly the car's velocity vector can be rotated

#

when drifting, your velocity rotates towards where the car is facing very slowly

ashen yoke
heady iris
#

i see the overload to actually set it

#

i'm just concerned about getting the right index

#

i guess i can just add an int field to specify which slot to target

#

there's probably no other sensible way to do that

ashen yoke
#

can be something like

class RendererData : MonoBeh
{
    public IReadOnlyDictionary MaterialIndexMap => _matIndexMap;
}
#

cache it once, small component, generic

#

overkill prob

#

simple Find on the array is faster

celest sable
heady iris
ashen yoke
#

yeah

heady iris
#

it would compare the instanced materials to its material and think they're all wrong

ashen yoke
#

yeah just IndexOf

#

maybe nice extension method

#
public static bool TrySetPropertyBlock(this MeshRenderer, MatPropBlock, Material)
{
    // Array.Find etc
}
#

false if no mat found

#

also probably should be done without ref, since refs wont match on mat clones

#

some shader/name/id combo

heady iris
#

Yeah, that's the fundamental problem

ashen yoke
#

custom shader?

#

can bake some id into it

#

theres probably a better mechanism but i dont know

heady iris
#

the barrel recoils a little too much, but that's another problem...

ashen yoke
#

@heady iris

#
    public Material mat;

    // Start is called before the first frame update
    void Start()
    {
        var clone = GameObject.Instantiate(mat);

        Debug.Log(mat.ComputeCRC());
        Debug.Log(clone.ComputeCRC());
        Debug.Log(mat.ComputeCRC() == clone.ComputeCRC());
    }
#

at least this works for simple clones

heady iris
#

huh, I never knew about that method

ashen yoke
#

yeah changing any prop fails it

#

as expected

heady iris
indigo haven
#

Hi, good day.
I have a problem, i have various coroutines that do stuff and all of them share a piece of code (the yield part).
Is there any way of making that code into a function or something to prevent duplicated code?
Code examples:

// Coroutine 1
public static IEnumerator ArbolBinario(Laberinto laberinto, float probabilidadPrimeraDireccion, DireccionesEnum direccionVertical, DireccionesEnum direccionHorizontal)
    {
        foreach (Celda celdaActual in laberinto.Celdas)
        {
            // stuff
            // Duplicated code 
            if (EjecuccionPorPresion)
            {
                yield return new WaitUntil(() => EjecutarUnaVez);
                EjecutarUnaVez = false;
            }
            else
                yield return new WaitForSeconds(periodoIteracion);
            // stuff
        }        
    }
// Coroutine 2
public static IEnumerator AldousBroder(Laberinto laberinto, Celda celdaInicial)
    {
        // Stuff
        while (laberinto.GetNumCeldasSinVisitar() > 0)
        {
            // Stuff
            if (EjecuccionPorPresion)
            {
                yield return new WaitUntil(() => EjecutarUnaVez);
                EjecutarUnaVez = false;
            }
            else
                yield return new WaitForSeconds(periodoIteracion);
            // Even more stuff
        }
    }
heady iris
#

it's small enough that I wouldn't really bother with extracting it

indigo haven
#

Its repeated in like 5 coroutines thats why it bothers my a little

heady iris
#

i guess you could make a function that just returns EjecutarUnaVez

indigo haven
#

Could you elaborate a bit more please?

somber nacelle
#

could also just make that bit its own coroutine and just yield that coroutine in all of the other ones that use it

indigo haven
#

Ummm im going to try that

heady iris
indigo haven
#

yeah

heady iris
#
bool Ready() => EjecutarUnaVez;
#

now Ready is a function you can pass to WaitUntil

indigo haven
#

Its a bit more complicated.
I have to wait either for that bool to be true if another bool is true or wait for a fix amount of time if not

heady iris
#

oh, I get it

#

the whole if/else

indigo haven
#

Yeah but dont worry. boxfriend solution works fine and i just need it to look good so no need for better solutions.
Thanks for the help you two btw

heady iris
#

yep, sounds good!

fresh stream
#

i have made a "custom" editor UI for my serialized objects to make it easier to see what's happening, though i have run into a problem where unity doesn't save the content. online i found something about the "SetDirty" function although i am not entirely sure about how to use it, could someone give some examples?

wild warren
#

i have two scripts, each one of them has some stuff in it, how can i make one of them to run before the other ???

oblique spoke
heady iris
#

it is likely that you're not telling Unity that you've changed things

fresh stream
# heady iris show your code.

most likely not optimal but here:

[CustomEditor(typeof(Dialogue))] public class DialogueEditor : Editor 
{
    private SerializedProperty options;
    private SerializedProperty dialogueTextArea;

    private void OnEnable()
    {
        options = serializedObject.FindProperty("options");
        dialogueTextArea = serializedObject.FindProperty("dialogueText");
    }

    public override void OnInspectorGUI() 
    {
        Dialogue dialogue = target as Dialogue;

        dialogue.hasOptions = GUILayout.Toggle(dialogue.hasOptions, "Does This Dialogue Have Options?");

        if(!dialogue.hasOptions)
        {
            Debug.Log(dialogue.speaker);
            dialogue.speaker = EditorGUILayout.TextField("Speaker Name:", dialogue.speaker);
            dialogue.speakerSprite = EditorGUILayout.ObjectField("Speaker Sprite:", dialogue.speakerSprite, typeof(Sprite), true) as Sprite;
            EditorGUILayout.PropertyField(dialogueTextArea);
            
            GUILayout.Space(20);

            dialogue.lastDialogue = GUILayout.Toggle(dialogue.lastDialogue, "Is This The Final Dialogue?");

            if(!dialogue.lastDialogue)
            {
                dialogue.nextDialogue = EditorGUILayout.ObjectField("Next Dialogue:", dialogue.nextDialogue, typeof(Dialogue), true) as Dialogue;
            }
        } else 
        {
            EditorGUILayout.PropertyField(options);
        }
    }
}
fresh stream
#

this was my first attempt at anything editor related

heady iris
#

it's a lot, yeah :p

wild warren
heady iris
#

I actually can't confidently answer this one

#

i can answer it, but i might be flat out wrong :p

oblique spoke
heady iris
#

Less clear on when you aren't using property fields

fresh stream
#

the solution was close, but what you said helped me realise what i had to lol. i just added

EditorUtility.SetDirty(serializedObject.targetObject);
```to the bottom of the editor script
#

thanks!

#

actually that doesn't seems to work for everything except the property fields

#

so i will just slide in what you wrote as well

#

that works

#

many thanks again!

indigo haven
#

Hey correct me if im wrong (which is probably the case) but:
The slider has a OnValueChange method that activates when the value changes. If i have a method in a class that gets called whenever that happens, do i need to have the slider inside the class?
The documentation says that i need to have the slider and add a listener but i have doubts

simple egret
#

Nope you can just have the method

indigo haven
#

And i can extract the value of the slider from the method just as a parameter right?

simple egret
#

Yep, if it takes a float your method will appear under the "Dynamic Float" section in the Inspector

indigo haven
#

Thanks for the help, it works

wild pivot
#

Hello all, I have an issue within my game where when I move the connected anchor of a hingejoint using a script, the hinge joint never moves.

Within the editor if I do this using the same script it works perfectly, however in builds it does not move the hinge. I have also installed debugging code, and can see from player.log that the connected anchor is actually changing to match what i want. The joint just never moves.

heres a screenshot of my hinge joint setup in case ive missed something obvious

#

is there perhaps a way of moving hinge joints which i have missed?

tawny elkBOT
#
Posting code

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

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

wild pivot
#
public class TargetController : MonoBehaviour
{
    [SerializeField] private Transform _targetHolder;
    [SerializeField] private HingeJoint _targetAnchor;
    [HideInInspector] private float _amplification = 1;
    [HideInInspector] private float _z;
    [HideInInspector] private float _zDifference;
    [HideInInspector] private Vector3 _anchorIntended;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        _zDifference = _targetHolder.position.z - _targetAnchor.connectedAnchor.z;
        _z = _targetAnchor.connectedAnchor.z + (_zDifference * _amplification);
        _anchorIntended = new Vector3(_targetAnchor.connectedAnchor.x, _targetAnchor.connectedAnchor.y, _z);
        _targetAnchor.connectedAnchor = _anchorIntended;

        Debug.Log(_targetAnchor.connectedAnchor);
        //Debug.Log(_anchorIntended);

        _targetAnchor.autoConfigureConnectedAnchor = true;
        _targetAnchor.autoConfigureConnectedAnchor = false;
    }
}```
#

it really doesent do much

#

if im honest i think im doing this just completely wrong, i mean it works but this method is awful

leaden ice
# wild pivot ```cs public class TargetController : MonoBehaviour { [SerializeField] priva...

Not really an answer to your question but:

    [HideInInspector] private float _amplification = 1;
    [HideInInspector] private float _z;
    [HideInInspector] private float _zDifference;
    [HideInInspector] private Vector3 _anchorIntended;```
Why did you need to make these fields, why not just local variables? You even went out of your way to add an extraneous `[HideInInspector]`
#

anyway - what are you trying to actually do with this code

wild pivot
#

yea my formatting is kinda odd not sure why i did it like that, made this ages ago

leaden ice
#

I mean that's not formatting, it's a functional difference of using instance variables instead of local variables.

wild pivot
# leaden ice anyway - what are you trying to actually do with this code

i have a chain of 2 hinge joints which im using to pivot an object, imagine holding a piece of paper at the top and moving your hand back and forward.

To then move this chain of hinge joints I move the top one by changing its connected anchor position. This works fine in the editor however doesent work at all in builds

leaden ice
#

shooting range target?

wild pivot
#

precisely

leaden ice
#

Can't you just move the top thing via the physics engine and everything will work as expected?

#

although it seems like you don't have a connected body configured for the joint(s)?

wild pivot
#

how would i do that? I couldnt figure that out when i originally made this so did it this way

leaden ice
#

via Rigidbody velocity or MovePosition

wild pivot
#

yea i dont use a connected body i dont really know how they work either. Hinge joints are a bit of a mystery to me

leaden ice
#

and connect them to each other via the joints

#

that's the correct setup

wild pivot
#

hm ok, at the moment my bottom hinge is connected to the top hinge with a connected body. Where would I connect the top hinge to?

This is my hirearchy, the child called target is the actual bit of paper

magic harness
#

Guys

#

Quick question

#

When i serialize a custom class, does unity automatically constructs the class?

#

do i need to call a constructor?

leaden ice
magic harness
#

awesome, ty!

indigo haven
#

In the context of having an slide and a TextMeshPro that shows its value, having this inside the text that its supoused to show the slider value:

public TextMeshPro PorcentajeText;
    void Start()
    {
        PorcentajeText= GetComponent<TextMeshPro>();
        PorcentajeText.text = "0%";
    }

    public void UpdatePorcentaje(float newValue)
    {
        PorcentajeText.text = Mathf.RoundToInt(newValue * 100) + "%";
    }

I get this problem: NullReferenceException: Object reference not set to an instance of an object in the UpdatePorcentaje line.

#

Any idea why? (Note: The method is asigned in the OnValueChange of the slider.

simple egret
#

PorcentajeText did not have a value. If you drag-drop the TMP, then you don't want the GetComponent in Start that will overwrite its value

indigo haven
#

You suggest me to drag the object rather than get it?

simple egret
#

Well your field is public for that reason, I guess

#

So it's visible in the Inspector, so you can drag-drop

indigo haven
#

The script is in the text that i want to check and i made it public to try to make it work but i will try this

leaden ice
simple egret
#

GetComponent searches the object this script is on, not another one. So if you don't have a TMP aside this script, GetComponent will fail and return null

leaden ice
#

You probably want TMP_Text

indigo haven
simple egret
#

Maybe, what's the text though, you might be trying to get the wrong type

#

What does it look like in the Inspector?

indigo haven
#

Yeah it was the Type, sorry for the confusion, PraetorBlue was right.
(A lot of TextMeshes to know xd)

#

Thanks for the help.

simple egret
#

Cleanup, since you now use GetComponent there's no need for the field to be public, this will prevent bugs in the future

#

Bugs where you don't remember how the script works, you drag-drop and it doesn't work

dusk apex
#

You'd just get slightly harder to debug errors if the component is missing and using get component πŸ˜›
In a way, you could consider inspector referencing to be an explicit reference whereas get component would be implicit (it's implied that this object should have the necessary component).

timid canyon
#

Hey! I am new to unity and I am trying to learn it with
Game Maker's Toolkit's tutorial (https://www.youtube.com/watch?v=XtQMytORBmM). Doing everything with video, I encountered small problem. Doing flappy bird game, my pipes are not spawning as I would wish. Basically it looks like this:

GMTK is powered by Patreon - https://www.patreon.com/GameMakersToolkit

Unity is an amazingly powerful game engine - but it can be hard to learn. Especially if you find tutorials hard to follow and prefer to learn by doing. If that sounds like you then this tutorial will get you acquainted with the basics - and then give you some goals to learn ...

β–Ά Play video
#

wait I cannot send that file in video format

#

the script looks like this

using System.Collections.Generic;
using UnityEngine;

public class PipeSpawnScript : MonoBehaviour
{
    public GameObject pipe;
    public float spawnRate = 2;
    private float timer = 0;
    public float heightOffset = 10;

    // Start is called before the first frame update
    void Start()
    {
        spawnPipe();
    }

    // Update is called once per frame
    void Update()
    {
        if (timer < spawnRate)
        {
            timer = timer + Time.deltaTime;
        }
        else
        {
            spawnPipe();
            timer = 0;
        }

    }

    void spawnPipe()
    {
        float lowestPoint = transform.position.y - heightOffset;
        float highestPoint = transform.position.y + heightOffset;

        Instantiate(pipe, new Vector3(transform.position.x, Random.Range(lowestPoint, highestPoint), 0), transform.rotation);
    }
}```
timid canyon
timid canyon
#

oh I didn't see that

potent sleet
#

also your video needs to be mp4

dusk apex
#

First clarify in words what's the issue (although it's obviously spawning to the left of the bird that's the issue)

timid canyon
dusk apex
#

Yeah, move to beginner coding.

timid canyon
#

alr

potent sleet
timid canyon
#

okau

swift falcon
#

i'm completely new to unity and when launching my first project i have an error at the bottom, how do i go about getting rid of this or is this expected seeing as though i haven't done anything with it yet?

leaden ice
#

(hint: read the full error)

#

open the console window

swift falcon
leaden ice
#

or uninstall it if you don't plan to use it.

swift falcon
potent sleet
#

nice to see unity is shipping new editor templates with broken VC package

leaden ice
#

Yeah have been for weeks

#

it's very annoying

rare slate
#

In the below Location class, specifically when the constructor is called, what is going on? There is an expression body member operator that is initializing the object as a string?

#

public class Location
{
private string locationName;

public Location(string name) => Name = name;

public string Name
{
get => locationName;
set => locationName = value;
}
}

leaden ice
#

the ultimate effect here is you will have a Location object with locationName set to whatever string was passed into the constructor

normal glade
#

Hello, I'm making a WPF app and I would need help to review my code, I know it's Unity but I don't know elsewhere to ask this, thanks in advance

simple egret
tawny elkBOT
simple egret
#

!cdisc

tawny elkBOT
rare slate
magic harness
#

Hey guys, im working on a 2D game. The project is still very small and my fps is absolutely garbage.
I got 230 with the player character not moving, without any 2d lights on the scene, 160 with the character moving and if i enable lights.
Ive gone into the profiler, enabled method names, and my methods are okayish, the worst one takes 0.018ms to complete so... im pretty lost as to what is happening. Any tips are appreciated

heady iris
#

there's going to be some constant cost per-frame

#

so your game won't go to 3,000 FPS even if you're just rendering one square

#

i would only be concerned if the game starts bogging down significantly as you add small amounts of content

magic harness
#

Sure. I can understand that. but it seems utterly ridiculous to have this amount of FPS with what im doing

heady iris
#

230 fps is a lot of frames per second

#

the cpu is screaming at the gpu and the gpu is screaming at the cpu and it's desperately working to fill the screen with pixels 230 times per second

magic harness
#

this is peaking me at almost 30 fps on a 2D game, with an NVIDIA 2060 and a ryzen 5 3600. Seems pretty crazy to me

soft shard
#

Your hardware (and possibly background applications, like a antri-virus running a scan or Steam downloading) can have a big affect on framerate as well - both the Profiler, and just the Editor in general also add overhead, every window (like the Scene, Game, Hierarchy, custom editors, etc) also add overhead (albeit, at different rates) so its good to test your frames in a build as well, which should have better frames, depending if you have VSync enabled or limited the Application.targetFrameRate, or playing in a different Screen.Resolution, all can affect framerate, in addition to the limitation of your hardware

mossy snow
#

but profile an actual build first

heady iris
#

I saved a few ms in one of my games when i realized that i was never actually deactivating UI that wasn't shown...

#

it was SmoothDamping towards 0 alpha, and it was supposed to deactivate the panels at 0 alpha

#

...so it'd wind up at like 0.0006 alpha, slowly trickling towards 0, and never actually deactivate

soft shard
#

Did you end up fixing that with a Mathf.Approximetly(..., 0) or just checking if its < some small decimal?

heady iris
#

I switched to lerping

#

much more predictable behavior

#

and it looked just fine

magic harness
#

On a build, it is capped at 60 FPS

soft shard
#

Is your Application.targetFrameRate also capped to 60? (maybe by default, if you didnt change it)

mossy snow
#

if desktop, disable vsync. If mobile, that's likely the max refresh rate of the screen and you can't change it

magic harness
#

i just set Application.TargetFrameRate = 300 on a script, on awake(). and it caps me at 120 now

heady iris
#

you can attach the profiler to a build

magic harness
#

yeah... okay. I just set vSync to 0 as well and with 30 light sources around the scene i dont get less than 120 FPS. So i guess not horrible

#

uhm.. how?

heady iris
#

i forget the specifics

#

you can look it up, though :p

#

i mostly just profile in the editor because i care about relative cost, not absolute cost

#

hmm, my function is taking 80% of the player loop

magic harness
#

uhm.. i can understand that

#

yeah i can't even find any of my methods there

#

so i guess they are good

#

its crazy to see how much overhead unity is actually taking... and how expensive 2D lights on the URP are. pretty crazy stuff.

#

but yeah... i guess there isn't a whole lot i can do about it

mystic ferry
#

if I have items that are represented with SOs, and then I have corresponding prefabs associated with them (like a Stick SO with crafting data, and a Stick prefab that has a sprite renderer so sticks can be placed throughout the world), how do I combine these two with an inventory for a complete system? I thought about using a dictionary and an array, where the array stores SOs and the dictionary's k/v pair is SO/prefab, but then I didn't know how to handle items that have a stack size (or how to handle serializing the inventory, but that's a problem for later)

#

am I mostly on the right track or am I way off? what am I looking for here

tough storm
#

not sure if this is the spot for it, but if anyone has tips on how to do CI/CD for mobile, that would be appreciated

tough storm
#

So, in terms of how to store an inventory with that in mind, think about what you may want to add to the SO in order to make your life easier on the "view" side of things. Or, think if you need to use SO's at all, there could be other options. Personally, I think i'd have a datastructure that encapsulated the information I want to store (maybe the SO) and the quantity of that item

#

This simplifies the problem down to being a one dimensional list instead of multiple containers and container types

#

other things you could add to your SO for your system are the UI Image you want to use to display the item, the name of the item, other data you want to show

#

so yeah, i like to use prefabs in a way that is modular, where you could pop in whatever SO you want and have it change the resulting UI element

verbal oxide
#

Moving this to this channel

I have a 2d isometric grid and tilemap that has grid tiles painted on it. I want to put my pathfinding script in here which uses A* as well as the NPC script that uses the pathfinding.
Here is my Pathfinding script and where i call on it in NPC.cs. sorry in advance for the dump lol. the prints show it scanning 9000 tiles but never returning a path that isnt empty
https://pastebin.com/3TQN2qn7

cold parrot
mystic ferry
#

is that typically how they're handled? I'd look at videos about them but they're all over 30 minutes long and I can't really get the energy to sit through them

cold parrot
# mystic ferry is that typically how they're handled? I'd look at videos about them but they're...

There is no typical architecture, different types of games have different needs. SOs and prefabs are just an easy way to make all this config editable/explorable by designers. I'd be careful with creating too many different SO types, can get confusing/messy. Its a good place to start though, as you can always build tools around an architecture that is already properly modularized and composable.

mystic ferry
cold parrot
#

if you use a singleton primarily to get easy access to an object instance you are misusing the pattern

swift falcon
#

I'm trying to find the code for the Move function of the CharacterController class, because I'm working with some movement code I found, but wanted to integrate it with my custom character controller scripts. Where can I find it?

swift falcon
#

Damn.

#

Here's the thing, I'm using AddForce to move my player controller, and I think that's interfering with the movement scheme.

cold parrot
swift falcon
#

Yeah I figured.

wild pivot
# leaden ice You would need each piece to have a Rigidbody

@leaden ice sorry to ping but i have a question on this, ive now set the top hinge to move my rigidbody move position, however this causes the target to rotate and then get like stuck in the ceiling lol

    void Start()
    {
     rb = topHinge.GetComponent<Rigidbody>();
    }

    void Update()
    {
        float _zDifference = _targetHolder.position.z - topHinge.transform.position.z;
        float _z = topHinge.transform.position.z + (_zDifference * _amplification);
        _destination = new Vector3(topHinge.transform.position.x, topHinge.transform.position.y, _z);

     rb.MovePosition(_destination);
    }
swift falcon
#

That's why I need to change some stuff around.

#

I'm looking into CPM-style movement (from Quake 3 Arena), but the guy uses the built-in CharacterController component. The collider that it generates interferes with the projectiles I fire from my weapons.

cold parrot
wild pivot
#

im just trying to be polite πŸ˜›

cold parrot
swift falcon
#

πŸ…±οΈruh

wild pivot
cold parrot
# swift falcon I'm looking into CPM-style movement (from Quake 3 Arena), but the guy uses the b...

you could have a look at KCC if you are serious about your movement, it has a great implementation for all the tricky bits (CharacterMotor) and a very nice example controller to learn how to use it properly (https://assetstore.unity.com/packages/tools/physics/kinematic-character-controller-99131)

Get the Kinematic Character Controller package from Philippe St-Amand and speed up your game development process. Find this & other Physics options on the Unity Asset Store.

heady iris
#

it's been nice for me, so far

#

i like how you can swap out the controllers

#

i'm planning to use that to implement different movement abilities

cold parrot
#

haven't met a person that doesn't love that thing

lilac token
#

i am working on a object pool for my game and i am having a problem that is when the queue starts from the top again after it reachs last object my bullets dont collide with anything ..here are the function from both the scripts ``` public GameObject SpawnObject(string tag)
{
if (!objectPoolDict.ContainsKey(tag))
{
Debug.LogWarning("Pool with tag " + tag + " doesn't exist.");
return null;
}

    GameObject spawnedObject = objectPoolDict[tag].Dequeue();
    spawnedObject.SetActive(true);
    return spawnedObject;
}

public void DespawnObject(GameObject objectToDespawn, string tag)
{
    objectToDespawn.SetActive(false);
    objectPoolDict[tag].Enqueue(objectToDespawn);
}

private void SpawnBullet(Vector3 position, Quaternion rotation)
{
GameObject bullet = ObjectPooler.instance.SpawnObject("Bullets");
if (bullet!= null)
{
bullet.transform.position = position;
bullet.transform.rotation = rotation;
bullet.GetComponent<Bullets>().BulletData = weaponData.BulletData;

    }

}
private void OnTriggerEnter2D(Collider2D collision)
{
    if (isDead)
        return;
    isDead = true;
    var hittable = collision.GetComponent<IHittable>();
    hittable?.GetHit(bulletData.Damage, gameObject);
    if (collision.gameObject.layer == LayerMask.NameToLayer("Obstacle"))
    {
        Debug.Log("Hit wall");
        ObjectPooler.instance.DespawnObject(gameObject, "Bullets");
        
        HitObstacle(collision);
    }
    if (collision.gameObject.layer == LayerMask.NameToLayer("Enemy"))
    {
        ObjectPooler.instance.DespawnObject(gameObject, "Bullets");
        HitEnemy(collision);
        
    }
    ObjectPooler.instance.DespawnObject(gameObject, "Bullets");
    

}```
swift falcon
#

It looks interesting.

uncut tundra
#

Hi, I am following a tutorial on yt on how to make a 3d survival game, and i am on the inventory episode, and for the code, i am using IBeginDragHandler, IEndDragHandle, and IDragHandler, but when i drag, the object im dragging disapears until i let go of it, I will attatch a video of it. How do i fix this

#

This is my code

`using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class DragDrop : MonoBehaviour, IBeginDragHandler, IEndDragHandler, IDragHandler
{

//[SerializeField] private Canvas canvas;
private RectTransform rectTransform;
private CanvasGroup canvasGroup;

public static GameObject itemBeingDragged;
Vector3 startPosition;
Transform startParent;



private void Awake()
{
    
    rectTransform = GetComponent<RectTransform>();
    canvasGroup = GetComponent<CanvasGroup>();

}


public void OnBeginDrag(PointerEventData eventData)
{

    Debug.Log("OnBeginDrag");
    canvasGroup.alpha = 1.1f;
    //So the ray cast will ignore the item itself.
    canvasGroup.blocksRaycasts = false;
    startPosition = transform.position;
    startParent = transform.parent;
    transform.SetParent(transform.root);
    itemBeingDragged = gameObject;

}

public void OnDrag(PointerEventData eventData)
{
    //So the item will move with our mouse (at same speed)  and so it will be consistant if the canvas has a different scale (other then 1);
    rectTransform.anchoredPosition += eventData.delta;

}



public void OnEndDrag(PointerEventData eventData)
{

    itemBeingDragged = null;

    if (transform.parent == startParent || transform.parent == transform.root)
    {
        transform.position = startPosition;
        transform.SetParent(startParent);

    }

    Debug.Log("OnEndDrag");
    canvasGroup.alpha = 1.1f;
    canvasGroup.blocksRaycasts = true;
}

}`

heady iris
#

!code

tawny elkBOT
#
Posting code

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

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

potent sleet
dusk apex
tawny elkBOT
#
Posting code

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

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

craggy seal
#

Using photon, my code is having this issue for some reason

#

It has legit never been a problem in the past

#

My code worked perfectly like this for months now

#

and now its telling me theres a problem

dusk apex
#

You've probably got another class called Player

dusk apex
craggy seal
#

So basically, every time a player joins a room it will assign a player variable to the player who joined

#

and then I can use that to do other things

somber nacelle
dense cypress
#

thanks @somber nacelle

craggy seal
#

and it has worked flawlessly until today

dense cypress
#

will repost there

dusk apex
#

Move your mouse over Player, what's the type?

craggy seal
#

class Player

dusk apex
#

So it isn't a Photon.Realtime.Player.

craggy seal
#

no

dusk apex
#

And you're attempting to pass it to the base method which requires a Photon.Realtime.Player.

dense cypress
#

you can't cast Photon.Realtime.Player to Player

craggy seal
#

not trying to say you're wrong

dusk apex
#

As I suggested well above.

craggy seal
#

alr

dense cypress
craggy seal
#

ill check

dense cypress
#

but to use player inplace of that namespaces player, there would have to be references

dusk apex
#

Likely you did not have a Player class before and it was referring to photon player class prior

craggy seal
#

alrighty ty

#

yeah i am legitimately stupid

#

I checked

#

so sorry for wasting your time

#

issue is fixed lol

dusk apex
#

It's discord, ask and receive help.

plush valve
#

I have a code for my character to climb ladders by setting the collider of an object to levitate the character but it doesnt work and i dont know whats wrong?
lmk if you want me to send the code

somber nacelle
#

when asking for help with your code you should just assume you should send it. !code
also check out #854851968446365696

tawny elkBOT
#
Posting code

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

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

somber nacelle
#

you're gonna want to re-read the bot's message there, mate

plush valve
#

oh woops

placid kiln
#

hello I need help with a bug I am having in my game. So when I start the game in the main menu and start either the game or the tutorial it runs fine no issues but if I pause the game go to the main menu and decide to go back to either one of the scene it freezes but if i pause and unpause the game it works fine again. I wanna know how i can fix the freeze bug when loading back into that scene from before.

#

I would like to do a call and show anyone if anyone is willing to help me (I am sorry for asking of this)

somber nacelle
# plush valve https://paste.ofcode.org/UFPsxGvnWYjtGVJN58Xfsc

you probably don't want these lines:

else
{
  isClimbing = false;
  GetComponent<Rigidbody>().useGravity = true;
}

because if this object is touching more than one trigger collider every frame but only one of them has the Ladder tag then those lines will run

also you need to actually say what isn't working

plush valve
#

when the player walks to the ladder object it doesnt let it climb it act like a normal collider

somber nacelle
#

sounds like it's probably not a trigger collider

opaque vault
#
        GetComponent<Rigidbody>().velocity = Vector3.zero;

wouldn't this line just make your character sit still? (row 47)

somber nacelle
placid kiln
# plush valve whats the code?

that's the thing it doesnt say what code it is i dont have any red errors or yellow errors but the issue is caused and i looked online what to do

opaque vault
#

I didn't recognize that, lotta bloat in there. good catch.

placid kiln
#

im so confused and i cant find the dang solution

plush valve
placid kiln
#

i have 10 different scripts of code what would be easy to send you without clogging the chat with code

#

@plush valve

opaque vault
#

@plush valve had you set a Debug.Log in the trigger stay function to make sure it's registering?

somber nacelle
plush valve
plush valve
#

what did you name the scripts?

somber nacelle
#

!code

tawny elkBOT
#
Posting code

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

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

opaque vault
#

Did you attempt boxfriends solution J.OB?

plush valve
somber nacelle
cosmic rain
# placid kiln thank you

I'd suggest putting some debug logs in your code to see what's going on. Specifically in the TogglePause method, outputting the new state of the game(paused or not).

plush valve
# placid kiln thank you

you could add a check to see if the PauseMenu scene is currently loaded before pausing or unpausing the game

plush valve
somber nacelle
plush valve
#

oh that yeah its on

#

for the character aswell?

somber nacelle
#

and you are certain that it is acting like a solid collider instead? if so you probably need to show the regular movement code

plush valve
#

alr

#

its the 3d third person movement code

#

when creating a project

#

i used it as a base for the project

placid kiln
somber nacelle
#

you need to actually call that method when you return to the main menu

plush valve
#

set time scale 0 to false

#

with the trigger set on the character walks through the ladder

somber nacelle
#

if the character did not have a trigger collider before then it shouldn't now. the ladder would be the one that needs the trigger since you are relying on OnTriggerStay/Exit and you're supposed to be able to walk through a trigger because it's not solid

lilac token
#

anyone has any idea why after i object pool my bullet prefab it doesnt detects any collisions?

cosmic rain
#

Also, are you sure that it doesn't actually detect collisions and it's not a fault in your logic?

lilac token
lilac token
#
    {
        if (!objectPoolDict.ContainsKey(tag))
        {
            Debug.LogWarning("Pool with tag " + tag + " doesn't exist.");
            return null;
        }

        GameObject spawnedObject = objectPoolDict[tag].Dequeue();
        spawnedObject.transform.position = position;
        spawnedObject.transform.rotation = rotation;
        spawnedObject.SetActive(true);
        return spawnedObject;
    }

    public void DespawnObject(GameObject objectToDespawn, string tag)
    {
        objectToDespawn.transform.position = Vector3.zero;
        objectToDespawn.transform.rotation = Quaternion.identity;
        objectToDespawn.SetActive(false);
        objectPoolDict[tag].Enqueue(objectToDespawn);

    }```
lilac token
plush valve
#

SpawnObject object pool?

#

with tag

cosmic rain
# lilac token the queue of the bullet prefab

Ok, doesn't seem like there's any issue in the spawning/despawning itself. I'd check the faulty bullet's properties in the inspector. There are only that much reasons a collision could not be detected.

lilac token
# cosmic rain Ok, doesn't seem like there's any issue in the spawning/despawning itself. I'd c...
    {
        if (isDead)
            return;
        isDead = true;
        var hittable = collision.GetComponent<IHittable>();
        hittable?.GetHit(bulletData.Damage, gameObject);
        if (collision.gameObject.layer == LayerMask.NameToLayer("Obstacle"))
        {
            
            Debug.Log("Hit wall");
            ObjectPooler.instance.DespawnObject(gameObject, "Bullets");
            
            HitObstacle(collision);


        }
        if (collision.gameObject.layer == LayerMask.NameToLayer("Enemy"))
        {
            
            ObjectPooler.instance.DespawnObject(gameObject, "Bullets");
            HitEnemy(collision);
            
        }
        ObjectPooler.instance.DespawnObject(gameObject, "Bullets");
        


    }```
cosmic rain
#

Is this code not on the bullet?

placid kiln
#

I fixed it with the freezing issue

plush valve
#

cool

placid kiln
#

thank u for who tried to help @plush valve @somber nacelle @cosmic rain you guys were big help CRI

lilac token
lilac token
sour zealot
#

Im following a photon tutorial and i made these override voids OnPlayerLeftRoom() and OnLeftRoom() They do not work. Error: No suitable method found to override.

void basalt
sour zealot
#

wdym sir

void basalt
#

it means exactly what I said

sour zealot
cosmic rain
#

Probably too early to start with networking, if you don't understand inheritance

sour zealot
#

i do sort of understand it

#

but In the video

void basalt
#

clearly not if you're inheriting from monobehaviour

sour zealot
#

i have the exact code

#

but its photon

cosmic rain
#

Then you would know what the error tells you.

sour zealot
#

ah

cosmic rain
sour zealot
#

i need monobehaviourpuncallbacks

#

yeah that was it

sour zealot
quartz folio
#

just ask a question

sour zealot
#

yeah ik

#

im debugging first

quartz folio
#

Then why did you ping someone

sour zealot
#

because i was about to ask the question

quartz folio
#

Christ

sour zealot
#

and then im like: "oh lemme debug before I make myself look stupid"

#

alr

#

i debugged

#

and now i know

glossy basin
#

Hello there, probably this is not the right channel to ask, but how much space does github free plan allow to have on a private repo?

sour zealot
#

those two override functions are not being called

true palm
#

hey im getting this error: NullReferenceException: Object reference not set to an instance of an object
Weapon.Aim (System.Boolean p_isAiming) (at Assets/Scripts/Weapon.cs:300)
Weapon.Update () (at Assets/Scripts/Weapon.cs:115)

in this script: https://hatebin.com/fowikbjthc

I have looked it over and I have no idea why it's not working. If someone could help that could be great

glossy basin
#

is there any better free solution to github (not unity collab)

glossy basin
sour zealot
#

cool

#

ill take a look at the script

true palm
#

thanks

glossy basin
#

the scope specifically

sour zealot
#

you have to assign it in your inspector

glossy basin
#

you need to assign a scope or just add a null check

glossy basin
sour zealot
#

he has it at the top of his script

#

he probably didnt assign it

sour zealot
quartz folio
sour zealot
#

vertx

#

mind answering my questioin?

quartz folio
#

Yes

sour zealot
#

you do mind?

#

or u dont

cosmic rain
#

where is your question..?

glossy basin
#

not the #region SUS πŸ˜‚ @true palm

quartz folio
#

I mind. I'm not going to answer a question where literally no context is provided

sour zealot
#

ah alr

#

context being typed now...

quartz folio
#

Perhaps you could just type 1 paragraph instead of 50 unrelated messages

true palm
#

hey, I have to go for a little. I'm having dinner. If someone figures it out could you DM me the answer? If so that would be great

quartz folio
#

You have already been answered.

cosmic rain
sour zealot
#

In this script: ```cs
using System.Collections;
using Photon.Pun;
using Photon.Realtime;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class PlayerListItem : MonoBehaviourPunCallbacks
{
// Start is called before the first frame update
[SerializeField] TMP_Text text;
Player player;

public void SetUp(Player _player)
{
    player = _player;
    text.text = _player.NickName;
}

public override void OnPlayerLeftRoom(Player otherPlayer)
{
    if(player == otherPlayer)
    {
        Debug.Log("Destroyed Player Object");
        Destroy(gameObject);
    }
}

public override void OnLeftRoom()
{
    Debug.Log("Called OnLeftRoom Fucntion");
    Destroy(gameObject);
}

}

#

Boom

#

Context

quartz folio
glossy basin
sour zealot
#

cool

#

vertx

#

are u good at 3d modelling?

quartz folio
#

This is a programming channel

sour zealot
#

ik

#

lol

glossy basin
quartz folio
# sour zealot ik

Then why are you asking these random questions specifically to me, without any context, in the wrong channel, and as multiple posts instead of paragraphs? Are you trying to be as obnoxious as possible?

glossy basin
sour zealot
#

they are from the pun realtime

glossy basin
sour zealot
#

i just get a bit antsy at night cuz my ADHD medication wears off

valid vale
#

So I've got a UI bug in my game that I can't figure out, but I have figured out that it has something to do with how I'm calculating the width of UI elements. I've tried three different ways (all shown in the attached video) to find the width of this UI element, but for all of them it changes based on the screen size, and I don't know why. All I want is a consistent width of the UI element, no matter what the screen size is. Here's the code I have in OnDrawGizmos that's showing what is in the attached video:

{
    RectTransform rectTrans = AgentTabs[0].GetComponent<RectTransform>();
    float width = rectTrans.rect.width;
    float sizeDeltaWidth = rectTrans.sizeDelta.x;
    float rectSizeWidth = rectTrans.rect.size.x;

    Gizmos.color = Color.red;
    Gizmos.DrawRay(AgentTabs[0].transform.position, width * Vector3.right);

    Gizmos.color = Color.blue;
    Gizmos.DrawRay(AgentTabs[0].transform.position + (32 * Vector3.up), sizeDeltaWidth * Vector3.right);

    Gizmos.color = Color.green;
    Gizmos.DrawRay(AgentTabs[0].transform.position + (64 * Vector3.up), rectSizeWidth * Vector3.right);
}```
#

also, here's the inspector settings of the canvas it's attached to

steep shore
#

MOBA Character/Ability Architecture

deep oyster
#

not sure if this goes in a different channel. There's so many channels lol.
So I'm trying to display text on this sign sprite, and google said I should use a TextMesh component on a child object. Only problem is, I can't seem to set it to the right layer. It's there, but it's behind my background object.

#

The components don't seem to have a field to set that, and setting the Layer for the object itself didn't do anything

languid crane
deep oyster
#

Like, z transform? No values work

languid crane
#

yeah, z, try going to 3d view and moving it in front of the sign

deep oyster
#

why is it facing backwards

languid crane
#

It seems to be working fine when i try to recreate it, not sure why

#

it does glitch out a little bit when the two objects are close though, maybe try pulling the text object further forward?

deep oyster
#

@languid crane when you recreated it, is your text visible from both sides if you go to 3d view?

languid crane
#

yes