#archived-code-general

1 messages · Page 9 of 1

woeful leaf
#

Because the inputs are seperate instances of the methods so therefore the vector not being combined, and thus that being the problem?

#

Because I need the combined vector and normalise that?

fluid kettle
#

yup

woeful leaf
#

How would I go about that though

#

With this code

fluid kettle
#

if you press W and A you want to sum the Vectors for W and A and not process them individually

woeful leaf
#

So I just have to rewrite most of it then

#

Hmm

fluid kettle
#

perhaps something like this?

public static Vector2 ProcessPlayerMovementToVector(Vector2 vector, in float multiplier, in Axis axis, in Polarity polarity)
    {
        vector.Normalize();
        
        vector = axis == Axis.X
        ? new Vector2((int)polarity * multiplier, vector.y)
        : new Vector2(vector.x, (int)polarity * multiplier);

        return vector;
    }

    private void MoveOnKeyPressed(KeyCode key, Axis axis, Polarity polarity, KeyCode key2 = null, Axis axis2 = null, Polarity polarity2 = null)
    {
        If(key2 ==null && axis2 ==null && polarity2 == null)
        {
            // Handle single Button Movement
            if (!Input.GetKey(key)) return;

            rb.AddForce(ProcessPlayerMovementToVector(rb.velocity, movementSpeed, axis, polarity));

            onMove?.Invoke(axis, polarity);
        
            print(rb.velocity.magnitude);
        }
        else
        {
            //Handle dual Button Movement
        }
    }

    private void UpdateMovement()
    {
        MoveOnKeyPressed(W, Axis.Y, Positive);
        MoveOnKeyPressed(A, Axis.X, Negative);
        MoveOnKeyPressed(S, Axis.Y, Negative);
        MoveOnKeyPressed(D, Axis.X, Positive);
        MoveOnKeyPressed(W, Axis.Y, Positive, A, Axis.X, Negative);
        MoveOnKeyPressed(W, Axis.Y, Positive, D, Axis.X, Positive);
        MoveOnKeyPressed(S, Axis.Y, Negative, A, Axis.X, Negative);
        MoveOnKeyPressed(S, Axis.Y, Negative, D, Axis.X, Positive);


        rb.velocity *= friction;
    }
#

that would be one way

#

Can't guarantee if it works, but that would be an idea for your given code

terse venture
#

How would i animate this in a 2D game? There is no horizontal or vertical movement, so im not sure how id get those variables to make my player animate.

spark flower
#

im experiencing some inconsistencies with the wait time, sometimes its like it waits more, sometimes less

#

usually its like the 1st wait is more then the next waits are less

main shuttle
swift falcon
#

How come you aren't using Unity's Input system to manage the axis for you?

woeful leaf
swift falcon
#

ahh

woeful leaf
#

Yap, mistakes were made lmao

woeful leaf
#

Still same effects

swift falcon
#

it shouldn't be too hard to adopt into your script honestly

thin aurora
#

Rather create it in Update

woeful leaf
#

Albeit I don't use null since enums don't support null, so I just made a None for every enum

woeful leaf
thin aurora
woeful leaf
#

Also a slight problem is that I don't have infinite time

#

I might just run with the "exploit" being there, if I can't fix it with similar to my concurrent code

swift falcon
woeful leaf
#

I think I'll run with the exploit for now, unless someone has a genius way of fixing it with the current code. I already spent an entire day on trying to fix it I honestly can't afford spending more time on it 😅

swift falcon
#

man Gladiator is typing an essay

#
void Update()
    {
        float xMove = Input.GetAxisRaw("Horizontal"); // d key changes value to 1, a key changes value to -1
        float zMove = Input.GetAxisRaw("Vertical"); // w key changes value to 1, s key changes value to -1

        rb.velocity = new Vector3(xMove, rb.velocity.y, zMove) * speed; // Creates velocity in direction of value equal to keypress (WASD). rb.velocity.y deals with falling + jumping by setting velocity to y. 


    }```
#

that's an example I found online, the axis's Horizontal and Vertical should already exist

earnest gazelle
#

What method do you favor to detect the type of a gameobject? For example, you keep a list of building gameobjects. They have different types, so, different components attached to.
Using enums? check a specific component existing in gameobjects?

public class BuildingController{
   private List<GameObject> _buildings;
   public IEnumerable<GameObject> GetAll(){return _buildings;}

   public IEnumerable<GameObject> GetAllByType(BuildingType type){
         return _buildings.Values.Select(building => building.GetComponent<BaseBuilding>().Type == type);
   }
   
   public IEnumerable<T> GetAll<T>(){
         return _buildings.Values.Select(building => building.GetComponent<T>()).Where(component => component != null);
   }
}

or if you would like to keep them in a dictionary, what is your key? enum type or type?
_buildings = new Dictionary<BuildingType,GameObject> BuildingType (Enum)
_buildings = new Dictionary<Type,GameObject>

#

or keep them separately. Define different classes (generic) for each?

public class BuildingController<T> where T:BaseBuilding{
   private List<T> _buildings;
   public IEnumerable<T> GetAll(){return _buildings;}
}
thin aurora
#

Just store it as a GameObject/Object/object

#

GetType() will give their type

earnest gazelle
thin aurora
#

Pretty often applications just store as an object and then cast it back to the generic type. If this results in null the cast was invalid

thin aurora
earnest gazelle
#

new BuildingController<ResourceBuilding>().GetAll(); new BuildingController<ResidenceBuilding>().GetAll();

thin aurora
#

You can't get them all with the same generic type

earnest gazelle
#

They are different classes

thin aurora
#

Oh, you create one for every single type?

#

Why not store them all in a single controller?

earnest gazelle
#

BuildingController<ResourceBuilding> is a type, BuildingController<MilitaryBuiling> is another type

earnest gazelle
#
public class BuildingController{
   private List<GameObject> _buildings;
   public IEnumerable<GameObject> GetAll(){return _buildings;}

   public IEnumerable<GameObject> GetAllByType(BuildingType type){
         return _buildings.Values.Select(building => building.GetComponent<BaseBuilding>().Type == type);
   }
   
   public IEnumerable<T> GetAllByType<T>(){
         return _buildings.Values.Select(building => building.GetComponent<T>()).Where(component => component != null);
   }
}
thin aurora
#

I'd just create a single manager that stores them all

#

Less confusing than having multiple. You can then abstract the complicating away by properly defining the method to get each type.

earnest gazelle
#

now, I want filter it, I think you did not get my question

knotty sun
earnest gazelle
knotty sun
#

yes

#

List<BaseBuilding>

earnest gazelle
#

GameObject is evil, you access all components, completely true

#

I prefer to define a facade component keeping all component refs there

#

Now, how do you filter it by building type?

knotty sun
#

easy use _buildings[i].GetType().Equals(typeof(type I want));

earnest gazelle
#

enum type field inside or checking getcomponent or is checking on BaseBuilding

#

OK, thanks

thin aurora
#

It is probably better to just create a list of type Tuple<Type, BaseBuilding> instead of storing the whole gameobject

thin aurora
mossy minnow
#

why does Vector2.SmoothDamp need a ref for the velocity? and if i dont have a rigidbody on the object what should i put in there?

tawny jewel
#

can someone help me fix the script? ive been sitting on it for a while and im just getting more and more confused, the errors im getting is "target" does not exist in current context and "time" does not take the number of arguments: 1

using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(menuName = "Powerups/SpeedBuff")]
public class SpeedBuff : Powerup
{

    public float amount;
    public float lifetime;
    public override void Apply(GameObject target)
    {
        var birdScript = target.GetComponent<BirdScript>();
        Debug.Log("added effect");
        birdScript.StartCoroutine(time(birdScript));
    }

    IEnumerator time()
            {
                target.GetComponent<BirdScript>().circlecollider.isTrigger = true;
                Debug.Log("ability enabled");
                yield return new WaitForSeconds(lifetime);
                Debug.Log("ability disabled");
                target.GetComponent<BirdScript>().circlecollider.isTrigger = false;
            }

    
}
woeful leaf
#

On how to post code

#

Syntax highlighting

thin aurora
knotty sun
tawny jewel
#

sure, but the issue is its in polish and i happened to also fail installing the language from unity

#

so yea sorry about that

trim schooner
#

Stop using GetComponent<T>() all the time for the same thing. Do it once and cache the result

thin aurora
tawny jewel
#

thats what it looks like

thin aurora
#

And maybe do some lessons on basic c# because this is somethign you should understand

earnest gazelle
thin aurora
#

typeof(T) should equal the type you store

tawny jewel
#

theres just a lot to learn

thin aurora
#

Nothing wrong with learning before you do the project

tawny jewel
#

im doing both at once honestly, doing lessons and then occasionally trying to work on my floppy bird in unity

earnest gazelle
#

In methods, you cannot access variables of another method defined.
You have to store it in a field

tawny jewel
#

sorry for even asking but can someone just tell me what lines of code i should add? i wonna just finish that part so i can go back to reading tutorials lmao

thin aurora
tawny jewel
#

okay ill ask there i guess

small citrus
#

Hi, I have a question about the ScrollRect class
In the "OnScroll" method, the code is

            if (vertical && !horizontal)
            {
                if (Mathf.Abs(delta.x) > Mathf.Abs(delta.y))
                    delta.y = delta.x;
                delta.x = 0;
            }
            if (horizontal && !vertical)
            {
                if (Mathf.Abs(delta.y) > Mathf.Abs(delta.x))
                    delta.x = delta.y;
                delta.y = 0;
            }

Do you know why it is inverting axis if the value is higher than the original ?
This is causing the scrollrect to scroll vertical when I push the joystick left or right in XR.
I tried activating both axis to avoid this, but this is scrolling a little bit horizontal and it's not wanted.
Thanks

woeful leaf
small citrus
#

Sorry

swift falcon
#

Is there a way to open the Itunes library and import MP3 files during runtime?

spark flower
#

btw

#

why is this giving me null refrence?

knotty sun
#

And Line 47 of Macros is what?

swift falcon
#

OnGoldChange() by the looks of it

#

need to see that function

knotty sun
#

that aint gonna throw a null ref

swift falcon
#

Functions throwing a null ref :?

spark flower
#

thats what it says

swift falcon
knotty sun
#

ok, then your event is null

spark flower
#

like noone is calling it?

swift falcon
#

no its empty.

knotty sun
#

no like you have not filled it

simple egret
#

An event that has no subscribers will be null, yes

spark flower
#

yeah so noone is connected to it

swift falcon
#

any of you fine lads ever worked with the itunes library and unity together by any chance?

simple egret
spark flower
#

i see thanks

#

i just made the registrations in awake instead of start and now it works

#

ill use that aswell

#

can someone help me?
this is what i want to do. i have a value Val = 100; and i want to spread this value across an array Array = 5 but i want each array slot to hold a random value from Val
so, Array[0] = 32; Array[1] = 42; Array[2] = 3; etc.

#

anyway

#
        int totalscrollvalue = Macros.CastlePower;
        int[] scrollvalue = new int[scrolls];
        int increment = 0;
        int scrolllength = scrollvalue.Length;
        print($"total scroll value: {totalscrollvalue}");
        for (int i = 0; i < scrolllength; i++) {
            increment = totalscrollvalue / (scrolllength - i);
            scrollvalue[i] = i >= (scrolllength - 1) ? increment : Random.Range((int)(increment * .3f), increment);
            totalscrollvalue -= scrollvalue[i];
            print($"scroll value {scrollvalue[i]}");
        }```
#

this is the solution that works for me now

unreal temple
#

You want the elements of array to sum to val right?

#

This will do taht

#

Conceptually it's placing 5 markers randomly on a number line from 0 to 100, and then measuring the distance between them.

#

So you'll get a completely random distribution

#

Could be 0,0,0,0,100

#

Could be 20,20,20,20,20

#

Actually that solution is imperfect because all the values might end up the same

#

And then it will fail

#

You can fix that though if it's the right approach

simple egret
#

My try at it, seems like it works fine

int sum = 100;
int elems = 5;
int[] arr = new int[elems];

for (int i = 0; i < elems - 1; i++)
{
    int n = Random.Range(0, sum);
    arr[i] = n;
    sum -= n;
}

arr[^1] = sum;
woeful leaf
#

How come this is not recognised

#

Whilst in Unity it is

unreal temple
unreal temple
unreal temple
#

Is it VSCode?

woeful leaf
#

Unless it unconfigured itself again or smth

woeful leaf
woeful leaf
unreal temple
#

Not sure, but double check you have VS set as your external editor in preferences

#

And maybe regenerate project files

woeful leaf
unreal temple
#

(not sure, I don't use VS)

woeful leaf
simple egret
#

Yeah looks like a project file failure, where it doesn't include some files in the compilation

unreal temple
#

I'd def try regenerating project files and restarting VS though

woeful leaf
#

Where is that button again?

unreal temple
woeful leaf
#

Ah

#

Nop

#

Still doesn't like it

unreal temple
#

And also I think it has a bias towards the start of the array?

#

My probability skills are lacking so I could be wrong

woeful leaf
#

Still the same

unreal temple
#

that's annoying

#

Maybe you could try closing unity, deleting Library/ScriptAssemblies and reopening the project?

#

I'm not sure if that will help

#

But sometimes will fix weirdness like this

#

Worth a shot

woeful leaf
#

I really don't know how it's this broken I didn't do much

simple egret
unreal temple
unreal temple
#

Unity will regenerate it

#

It's safe to delete anything in library.

#

just trash the whole folder

woeful leaf
#

I deleted everything in the folder

unreal temple
#

sweet

woeful leaf
#

Is that not sufficient?

unreal temple
#

That's sufficient, yeah.

woeful leaf
#

Ah

unreal temple
#

Now reopen

#

And reopen VS after I guess

#

I don't really think this will fix your issue, but it's worth a shot

woeful leaf
#

Nop

#

Still dead

unreal temple
#

Where is the namespace coming from?

#

A DLL?

woeful leaf
#

Package

#

So somehow my IDE is not reading my packages properly

#

unlink the link I'll just paste it in the browser

#

Unless the bot picks that up too

unreal temple
sleek bough
#

Make sure you didn't create a class with the same name yourself. Some of the autoprompts in VS could've done it

unreal temple
#

That's an option for VSCode

unreal temple
spark flower
trim schooner
#

There's a refresh connection button somewhere in VS, which will refresh the solution

unreal temple
#

Only in reverse

#

Yours will bias towards 100

simple egret
#

Yeah it has a high bias towards the start of the array

woeful leaf
simple egret
woeful leaf
woeful leaf
muted idol
#

guys I want to find an animation clip by keyword in a list of animation clips enumerated from the animator. so I did this
_animator.runtimeAnimatorController.animationClips.Find((anim) => anim.name == "asereje");
the animation clip that has similar name is there but it returns null. did I do something wrong?

unreal temple
# simple egret Sums for 15k picks: `{ 741386, 371801, 185540, 92761, 108512 }`

this should be right:
@spark flower

var array = new int[5];
var val = 100;
for (var i = 0; i < array.Length; i++) {
  var value = Random.Range(0, val + 1 - i);
  for (var j = 0; j < i; j++) {
    if (value >= array[j]) value++;
  }
  array[i] = value;
}
Array.Sort(array);
for (var i = array.Length - 1; i > 0; i--) {
  array[i] -= array[i - 1];
}
#

I haven't run it.

#

But maybe you can plug this into your test @simple egret

woeful leaf
#

Afaik I never touched these checkboxes

unreal temple
woeful leaf
#

Yeah I was thinking of that, lemme check

unreal temple
#

@simple egret I just fixed a bug

#

in that code

#

mb

#

woulda been all zeroes

trim schooner
woeful leaf
#

Ah right

woeful leaf
# woeful leaf This?

I fixed it though, turns out this is the culprit - which is weird since it used to work

#

But then Ig it decided to stop working and I've to manually check that box

unreal temple
#

Probably working around some obscure bug

#

in the visual studio package

#

You should also check if you can update the vs package in your package manager

simple egret
simple egret
#

I got one 99, but it's mostly random

unreal temple
#

Well, there's some bug

#

That's what you get when you code directly into discord I guess

unreal temple
#

The final sohuldn't be random.

woeful leaf
#

Lemme see if I can break it again

#

Then see if installing that update will fix it

unreal temple
# simple egret I got one 99, but it's mostly random
var array = new int[5];
var val = 100;

// Pick random values in range [0, val].
for (var i = 0; i < array.Length - 1; i++) {
  // Select any value in range, subtracting the number of previously selected
  // values (as they are excluded).
  var value = Random.Range(0, val - i);

  // For every previously selected value exceeded, increment by one to prevent
  // collisions.
  for (var j = 0; j < i; j++) {
    if (value >= array[j]) value++;
  }

  // Store the adjusted value.
  array[i] = value;
}

// Set final value to max.
array[^1] = val;

// Now order values correctly.
Array.Sort(array);

// Measure the "distance" between each value and the one before it.
for (var i = array.Length - 1; i > 0; i--) {
  array[i] -= array[i - 1];
}
#

lol most ridiculous debugging loop

woeful leaf
unreal temple
#

The important thing is that you don't need to think about it for some indeterminate amount of time

woeful leaf
#

And then forget how I solved it previously and be stuck with the same problem eventually again KEKW

woeful leaf
# unreal temple Glorious

If I untick the box, and regenerate the project files, does it remove the old ones for the ones that are unticked?

vague slate
#

type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
Is there a way to obtain methods including inherited ones?

unreal temple
#

booya

unreal temple
#

I stayed up past my bed time for you

#

and the dream of a perfect distribution

ebon fern
#

Need Help Building Upon Dialogue System

spark flower
unreal temple
#

Basically what it does it repeatedly picks a random point in range, excluding points that have already been selected

#

Then it takes the difference between them to get the final values

#

For example if val is 10, it will pick a random number between 0 and 9

unreal temple
#

Very similar to how I do weighted probability

knotty sun
#

var value = Random.Range(array[i], val - i);

unreal temple
woeful leaf
unreal temple
woeful leaf
#

I removed the csproj files it generated for the package

#

But it still works

sweet current
# vague slate `type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonP...

BindingFlags.FlattenHierarchy ( https://learn.microsoft.com/de-de/dotnet/api/system.reflection.bindingflags?view=netstandard-2.1 )
Make sure to check compiling with IL2CPP if you intend to use that. Not all reflections work with that.

unreal temple
woeful leaf
#

What kind of sorcery is this, that it only needed to be generated once, and then just can be disposed again after

knotty sun
unreal temple
#

Perhaps the csproj wasn't properly regenerated when you hit the button

woeful leaf
spark flower
unreal temple
woeful leaf
unreal temple
vague slate
unreal temple
spark flower
#

you havent even tested this code

unreal temple
#

SPR did

knotty sun
unreal temple
#

That is exactly what this is doing

knotty sun
#

no, you are removing any value less than one already selected

unreal temple
#

What can I say?

#

It's shifting the selection forward to skip the values that have already been selected.

spark flower
#

i dont see how this code is useful it has 3 loops while in my code it has just one

woeful leaf
hollow stone
#

My initial thought would be something like this. But it surely has some flaws ^^
I liked your way of thinking with the distributing with cuts @unreal temple , but dislike the sorting : )

var totalBuckets = 10;
var totalValue = 100;
var totalTokens = 0;
var buckets = new list<int>();

for totalBuckets
    var tokens = roll(0, totalValue + 1);
    totalTokens += tokens;
    buckets.Add(tokens);


var finalValues = new list<int>();
foreach bucket
    var valuePerc = bucket / totalTokens;
    var value = Round(valuePerc * totalValue);
    finalValues.Add(value);
woeful leaf
unreal temple
spark flower
#

@unreal temple i think your just overcomplicating this thing

#

well i need to do this 3 times

#

3x3=9 loops in one frame

#

for no reason

#

and i will add more items

unreal temple
spark flower
#

so lets say i get to 20 items x 3 loops

#

60 loops

#

its not modifiable

unreal temple
#

What isn't?

spark flower
#

60 loops vs 20 loops

#

which one is better?

#

in one frame

unreal temple
#

The one that gives the correct result.

#

What is this line of reasoning

spark flower
#

optimisation kind

#

the 20 loops one gives correct resaults aswell

#

and is modifiable easily

unreal temple
#

Which code is better:

int Sum(int[] array) {
  return 0;
}
int Sum(int[] array) {
  var result = 0;
  foreach (var e in array) result += e;
  return result;
}
#

First has zero loops

#

Second has one loop

#

1 > 0

rain minnow
# spark flower optimisation kind

That's not an optimization. The results are different based on your one loop verse their 3 loops. The issue here is accuracy . . .

unreal temple
#

Therefore first is better?

knotty sun
unreal temple
vague slate
spark flower
unreal temple
spark flower
#

the one with less loops does the job

#

no need for 3 loops

unreal temple
spark flower
#

what accuracy are you talking about?

#

im talking to invader

unreal temple
spark flower
#

what about it

spark flower
#

just to force solve it through an idea

unreal temple
#

So that the result would be 9,8,10

knotty sun
#

exactly

unreal temple
#

Good catch

#

I'm not sure if that makes it insane though.

knotty sun
#

you need to store highest number so far

unreal temple
#

Perhaps there's a simpler way to structure it.

knotty sun
#

and if you are going to do that you might as well just restrict your random.range

unreal temple
#

Assuming that's meant to be array[i - 1]

#

I actually am not sure what you're going for here

#

array[i] is always 0 in the fresh array

knotty sun
#

so start val at val - Array.Length and increase it

#

indeed i-1

unreal temple
#

So your first value is in range [5, 100]?

knotty sun
#

no, val = 100
array.length = 5
range = 0 to 95
generated = 15
range = 16 to 96

#

etc

cinder kindle
#
[Package Manager Window] Cannot perform upm operation: Unable to add package [https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop.git?path=/Packages/com.unity.multiplayer.samples.coop#main ]:
  No 'git' executable was found. Please install Git on your system then restart Unity and Unity Hub [NotFound].
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()
[Package Manager Window] Error adding package: https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop.git?path=/Packages/com.unity.multiplayer.samples.coop#main .
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()

I get these errors whenever I want to add the package

https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop.git?path=/Packages/com.unity.multiplayer.samples.coop#main

I've tried restarting unity and nothings changed

unreal temple
#

I have a guide for this for my team

cinder kindle
unreal temple
#

Just install git-scm

#

It should do it for you

knotty sun
unreal temple
#

Basically you just need to install git

unreal temple
#

wrong code

#

Hm. Can't remember where I used this pattern, but somewhere at some time that made more sense.

unreal temple
cinder kindle
#

i did

unreal temple
#

Make sure you check the option to add to Path

#

If there is one

#

Otherwise just select all the recommended options

#

there are a lot of installation options

cinder kindle
unreal temple
#

You'll need to completely restart unity hub after installed installed @cinder kindle

cinder kindle
#

do i need to launch it

unreal temple
#

Not just unity

cinder kindle
#

task manager style?

unreal temple
#

It's just a program that unity is trying to run directly

#

It's a CLI application

#

Windows for some reason doesn't come with it

#

Unlike Linux/macOS and other *nix OSes

#

But make sure you fully exit unity hub and restart it or else it won't see the updated Path variable

cinder kindle
#

still not working

#

i task manager quit unity and unity hub

#

100 percent added it to path

#

@unreal temple

#
[Package Manager Window] Cannot perform upm operation: Unable to add package [https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop.git?path=/Packages/com.unity.multiplayer.samples.coop#main ]:
  Error when executing git command. fatal: invalid refspec 'main '
 [NotFound].
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()
[Package Manager Window] Error adding package: https://github.com/Unity-Technologies/com.unity.multiplayer.samples.coop.git?path=/Packages/com.unity.multiplayer.samples.coop#main .
UnityEditor.EditorApplication:Internal_CallUpdateFunctions ()
mellow sigil
#

You have an extra space at the end

hollow stone
#

@spark flower Here you go one solution in full code^^

    private List<int> BucketRandomizer(int totalBuckets, int totalValue)
    {
        var totalTokens = 0f;
        var buckets = new float[totalBuckets];

        for (int i = 0; i < totalBuckets; i++)
        {
            var tokens = Random.Range(0f, 1f);
            totalTokens += tokens;
            buckets[i] = tokens;
        }

        var outValues = new List<int>(totalBuckets);
        foreach (var tokens in buckets)
        {
            if(totalTokens == 0)
                continue;
            
            var valuePerc = tokens / (float)totalTokens;
            var value = Mathf.RoundToInt(valuePerc * totalValue);
            outValues.Add(value);
            totalTokens -= tokens;
            totalValue -= value;
        }

        // All buckets randomized 0
        if (totalValue > 0)
        {
            outValues[^1] = totalValue;
        }
        
        return outValues;
    }
unreal temple
#

Your URI is wrong

cinder kindle
spark stone
#

So esentially I have a missile going up and I want it to be when it gets close to a circle (black whole kinda) it gets sucked slughtly and and is being pulled by a graviational force, problem is I dont know how to rotate the missile towards the direction if being pulled if that makes sense. heres my current code ```cs
public float suckingForce = 10; // The strength of the black hole's sucking force
public float rotationSpeed = 1; // The speed at which the ship rotates around the black hole

public float radius = 5f;

Vector2 pullForce;

void FixedUpdate()
{
    // Find all objects within the black hole's radius
    Collider2D[] colliders = Physics2D.OverlapCircleAll(transform.position, radius);
    foreach (Collider2D collider in colliders)
    {
        if (collider.GetComponent<Rigidbody2D>())
        {
            float distanceToPlayer = Vector2.Distance(collider.transform.position, transform.position);

            Rigidbody2D rb = collider.GetComponent<Rigidbody2D>();
            pullForce = (transform.position - collider.transform.position).normalized / distanceToPlayer * suckingForce;
            rb.AddForce(pullForce, ForceMode2D.Force);
        }
    }
}```
unreal temple
spark stone
#

this would work for 2d?

tawny jewel
#

can anyone recommend any good site/program to learn c#

unreal temple
#

So your numbers will be more densely packed towards the higher end (on average)

#

It only solves the problem of collisions, but doesn't give an even distribution

#

Which may or may not matter

#

But it doesn't solve the same problem

#

Unless I'm misunderstanding

knotty sun
unreal temple
warped compass
#

I'm having an issue where the collision for the attack is sometimes delayed. Both the enemy and sword have a rigidbody with continuous collision.

When both collide the enemy is supposed to react with an animation and a knockback force. Sometimes it happens immediately like its supposed to, other times it is delayed by like half a second.

It doesn't seem to have anything to do with performace, it happens regardless if its running at 50 fps or 200.

The attack hitbox enables via an animation event, and is not having any issues with enabling from what I've seen.

Here's all the code associated with the collisions:

(Weapon script)

    {
        if (other.CompareTag("boss") || other.CompareTag("enemy"))
        {
            hitbox.enabled = false;
        }
    }```

(Enemy script)
```    private void OnTriggerEnter(Collider other)
    {
        if (other.CompareTag("blade") && health > 0)
        {
            knockback();
            endattack();
            anim.SetBool("attack", false);
            anim.SetBool("running", false);
            anim.SetBool("hit", true);
            hitcount = hitcount + 1;
            anim.SetFloat("hitcount", hitcount);
            health = health - 40;
            attackdelay = attackdelaydefault;
            attacking = false;
        }
    }```
I have no idea what I've done wrong, I've never had this issue before.

Thanks.
knotty sun
unreal temple
knotty sun
#

np

knotty sun
unreal temple
#

It's irrelevant really. The allocation of 100 is needless

#

You don't know how many times it will be called

knotty sun
unreal temple
#

I have, it's the same as mine without the optimisation

#

And without the bug you found

#

Which is fixable

knotty sun
#

it's not the same as your's at all and it addresses your question about distribution

unreal temple
#

It's the same algorithm, different implementation.

#

Picking from a set that excludes the previously selected numbers

knotty sun
#

except mine works and your's doesnt

woeful leaf
tough osprey
#

Any thoughts on Unity's GitHub integration via Unity directly https://unity.github.com/ vs Git command line via WSL? I'm used to command line at work, but curious if the Unity GitHub direct integration in Unity helps with some of the Unity aspects that I may not be aware of.

unreal temple
unreal temple
#

I don't want to have to open unity to use git

#

Use a GUI like git-fork or sourcetree

#

GitHub desktop is also an option

tough osprey
#

Any reason you'd recommend the GUI vs command line? Personal preference or is it better for Unity aspects like Large Files?

unreal temple
#

Very few people use git CLI directly

#

Just like beardy old Unix guys

#

And web dev hipsters who think it's cool

#

Being able to see your history is extremely valuable

tough osprey
#

hahaha, I use it exclusively at work, didn't realize that put me in a box 😛

unreal temple
#

I used to as well

#

Staging individual lines is a pain in cli, as is cherry pick etc

woeful leaf
#

Honestly I myself just use GitHub Desktop - it can be a bit limited in features, but if you really need to do something more advanced, you can always open up Git Bash to do something extra

#

(A git reset par example)

woeful leaf
#

I think sourcetree has more features

unreal temple
#

It's very good

woeful leaf
unreal temple
#

It's free if you don't mind the nag message

#

Then don't!

woeful leaf
#

Haven't tried git fork though

tough osprey
#

Well since this is a side project where I'm learning new things ... it's a good opportunity to try a new way to Git

unreal temple
#

Cli knowledge is great still for automation

#

Build and release pipelines

#

Etc

sonic harness
#

Does someone know what is cause of this problem
[4] The message header is corrupted and for security reasons connection will be terminated.

sonic harness
#

i dont thinks so. i tried changeing them

woeful leaf
#

What

simple egret
#

They need context on the error, like where did it happen, and what did you do to get it.
Currently, it's as if I said

I have an error can you help me fix it
No context, so can't help

agile brook
#

Hi, I want to make an AI navigation system based on waypoints. The AI spawns at one corner of the map and has to try to get to a target point, which is itself linked to a waypoint. Between the starting waypoint and the waypoint linked to the target, I want to search all the waypoint connections to figure out the path to take from start to end. Does anyone know the best way to begin implementing this?

hollow stone
sterile relic
#

BetterClickerPrice = Mathf.Round(BetterClickerPrice * 1.1f); whats the issue here, new to mathf libary

#
Error    CS0266    Cannot implicitly convert type 'float' to 'int'. An explicit conversion exists (are you missing a cast?)
#

thats the error

prime sinew
#

hover over it and see

sterile relic
#

float

leaden solstice
prime sinew
#

oh, hold on

#

what type is BetterClickerPrice

sterile relic
#

int

prime sinew
#

okay

#

Mathf.Round gives you a float, you're trying to assign it to an int

sterile relic
#

so i need a int return from round

leaden solstice
#

Use RoundToInt

prime sinew
#

that's the issue

leaden solstice
#

It's just same as (int)Mathf.Round but in prettier form

sterile relic
#

gotcha thank you

fluid kettle
candid kiln
#

Is there any way i can show my World Space on top of Screen Space?

thick socket
#
NumberSummoned = root.Q<Label>("NumberSummoned");
Debug.Log($"tmpOffer is null? {NumberSummoned == null}");
#

how is this null?

candid kiln
thick socket
#

UI Builder

#

2022 something

candid kiln
#

Ok

thick socket
#

found the issue...guess I should have included more code 😭

#

like 3 lines above that I had an unfixed if statement

agile brook
# hollow stone It's weird that you say that you want to search all the connections? Usually you...

I’ve never implemented A* before, but doesn’t it operate off distance to the target? I’m essentially trying to figure out a path between two waypoints, with the path being comprised of waypoints that have already been placed, and this means that the distance might not necessarily always decrease if the waypoint path winds around obstacles or something like that. I need this algorithm because many of the waypoints branch off and could be navigated multiple directions.

mossy minnow
#

hey everyone, so im trying to make a top-down movement controller, and i want to be able to control the friction of starting/stopping without affecting the max speed in any way.
right now im using:

        curVelDebug  = rbVel;```
but it seems that when i move the frictionAmount, it changes the max speed in strange ways
im just doing `rb.velocity = rbVel;` for actually setting the vel
prime sinew
mossy minnow
#

sry

#

things get buried very easily in these chats i find u-u

leaden solstice
#

Yeah forum channel when 😄

leaden solstice
#

It's return value is position

mossy minnow
#

sry dont fully understand that

vast flare
#

Heyo, so has anyone here used the strand hair physics solution?
If so any idea how to get the vertex data of the hair, im having no luck 😦

mossy minnow
#

so if i dont use the vel on the SmoothDamp how do i use it?

#

where does it return a position\

#

and what is that position

#

and how do i use it

uncut vapor
#

Any idea why a [SerializeField] private Image[] isn't showing in inspector?

thick socket
#

Im 80% sure that needs to be deleted

mellow sigil
#

Should've bet on the 20%

thick socket
#

😭

uncut vapor
#

I tried just without private, with public instead and it doesn't change nothing

mellow sigil
#

Do you have any errors in the console

uncut vapor
#

nope

late lion
uncut vapor
#

Oh yeah you're right lmao

mossy minnow
#

what would the best way to spawn multiple enemy types? i want to be able to instantiate a new enemy with a random enum (Melee, Ranged, Bow, Bomber)

orchid bane
leaden solstice
halcyon thorn
#

I am having trouble with Physics.CapsuleCastNonAlloc(...). It always returns 0 collisions.
The two sphere gizmos you see are at the bottom and top positions I pass in, radius is the same direction is a non-zero vector.
No special layer mask. maxDistance is 2f.
The objects with colliders I am trying to check against are on the Default layer.

I do not understand what is wrong here.

rain minnow
mossy minnow
leaden solstice
#

You don't need to modify or set anything for it, just keep the value as member field

rain minnow
woeful leaf
#

As far as I could tell, it didn't change anything

zinc parrot
#

Hey so when I have combined meshes due to them being Static, what data to I have access to from there?

halcyon thorn
#

this is the ground it's intersecting

#
        var bottom = CurrentState.Position + Vector3.up * radius;
        var top = CurrentState.Position + Vector3.up * (height - radius);
        var direction = _desiredPosition - CurrentState.Position;

        // Check for possible collisions
        var collisions = Physics.CapsuleCastNonAlloc(bottom, top, radius, view.forward, hits, 2f);
#
        Gizmos.color = Color.white;
        Gizmos.DrawSphere(CurrentState.Position + Vector3.up * radius, radius);
        Gizmos.DrawSphere(CurrentState.Position + Vector3.up * (height - radius), radius);

        Gizmos.color = Color.green;
        Gizmos.DrawSphere(CurrentState.Position + Vector3.up * radius + view.forward * 2f, radius);
        Gizmos.DrawSphere(CurrentState.Position + Vector3.up * (height - radius) + view.forward * 2f, radius);
#

first is the collision code, the second is the gizmos

#

collisions always returns 0

#

I think I figured it out. CapsuleCast works, CapsuleCastNonAlloc does not. It seems to be an issue with the fact that hits was not instantiated

rain minnow
#

i don't see where you initialize hits at all in your code. better to use this method as it doesn't generate garbage . . .

halcyon thorn
#

Yeah, that was the issue. I did not instantiate the hits array with anything, it was null. Figured it would throw an error but I guess not

halcyon thorn
#

Another issue now - hits[0].point returns (0,0,0)

#

even though hits[0].collider.gameObject.name returns the name of the object correctly

#

does it get cleared or something when accessed?

rain minnow
halcyon thorn
#
Debug.Log($"Hitting {hits[0].collider.gameObject.name}, {CurrentState.Position}, {hits[0].point}");
Debug.DrawLine(CurrentState.Position, hits[0].point, Color.green, 1f);
#

Hitting Floor, (-29.63, -0.04, 4.50), (0.00, 0.00, 0.00) every single time

#

hits[0].point is always the zero vector...

rain minnow
#

that is weird. is that the only hit or are there more?

halcyon thorn
#

the first hit is always the character itself, which I ignore

#

unless it hits something else

#

always returning zero vector for all hits

rain minnow
halcyon thorn
#

oops, you are correct. there is another one with the floor as well one sec

rain minnow
#

make sure you check if the collider from the RaycastHit is not null before attempting to access it . . .

halcyon thorn
rain minnow
#

and ensure the length of the buffer (array) can store the amount of colliders needed . . .

halcyon thorn
#
        Debug.Log("=============================");
        foreach (var hit in hits)
        {
            if (hit.collider == null) continue;
            Debug.Log($"Name: {hit.collider.name}, Point: {hit.point}");
        }
        Debug.Log("=============================");```
#

hits = new RaycastHit[5]; before every cast

rain minnow
#

move the cast position and check if hit.point changes . . .

halcyon thorn
#

won't it retain all the old raycast hits?

rain minnow
#

based on where it's at, it is hitting the floor at 0, 0, 0 world position . . .

halcyon thorn
#

the position of the character is nowhere near

rain minnow
halcyon thorn
#

it's not a list, so I just make a new one for now. I am just trying to get the thing to work first

#

oh wtf... it does it correctly but only once

#

Position: (-30.00, 0.00, 0.00), Name: Floor, Point: (-30.00, 0.00, 0.00)

#

then every subsequent time it's Position: (-29.98, -0.05, 0.11), Name: Floor, Point: (0.00, 0.00, 0.00)

#

okay so it seems that if the collider already intersects the capsule cast, it will say that the point is 0,0,0

#

that makes no fucking sense to me

halcyon thorn
#

why is this considered normal?

rain minnow
#

any colliders that overlap at the start of the cast have their normal set opposite of the direction, their distance set to zero and the point returned set to a zero vector . . .

halcyon thorn
#

that seems like something that should be mentioned in the docs or something

#

I'm not a mathematician and I can't inspect the source code to figure that out

rain minnow
#

it is in the docs, the problem is where. all the information is from the regular CapsuleCastAll, (for some weird reason) details are implied when using the NonAlloc version as the only difference is creating the buffer array yourself to save from garbage collection . . .

halcyon thorn
#

either way, it shouldn't return the zero vector if the comment states that RaycastHit.point will return the world space impact point where the ray hit the collider

#

either that or the comment should be more clear

#

ugh that is so frustrating, thanks for the help

rain minnow
halcyon thorn
#

yeah, I mean that it should be clear in the comment there

rain minnow
#

it doesn't cast bc a collider is already occurring . . .

rain minnow
halcyon thorn
#

oof

spiral geyser
#

Is there anyway to change SetActive of a gameobject while inside of a script in Unity?

#

like referencing a gameobject then setting something inside it to on?

#

Oh I am stupid

spiral geyser
#

lol I am stupid sorry

uncut vapor
#

I wanna make a grid made of lines
And I need to calculate the coords of each of the lines
I have a var for which line in the row is it, in which row is it, how big each line is, how much lines is there in a row and how much rows is there but I been trying to get the math right for last hour
Anyone got the solution?

marble halo
#

Anyone know how to make a skinned mesh renderer follow a ragdoll?

#

because if it doesnt the ragdoll will often turn invisible when looking at it

potent sleet
# marble halo

not really a code question.
you need colliders on each bone of the avatar

marble halo
#

I do, also where would be a better place to ask?

#

the problem is the cube doesnt move with the ragdoll

#

wait does that include the root bone?

potent sleet
craggy nova
#

Do I need to somehow put jump function (with rigidbody) in FixedUpdate if I am using the unity event in new input system?

#

I can't think how to do it

#

and tutorials don't seem to be doing so as well

left narwhal
#

seems all right

#

dont think it matters that much

desert shard
tulip silo
#

i have a raycast that i am using from the camera to detect items along with looking at them, this works, but the raycast goes through objects with other tags from the one i'm targeting, also some of the items won't turn off when i look away from them, or they will turn off as i'm moving and looking at them. if anyone knows what to do about this part then please let me know

potent sleet
tulip silo
#

the colliders are set up properly, and here's the code for the "logic" part of it

#

the done part is just from another trigger to check if the player is in the store or not, and seen is for the box collider being within the camera's vision at all

shut ridge
#

when it comes to netcode, is there a way to identify individual players

#

like some sort of playerid

pearl radish
#

Clients all have a client id

shut ridge
#

how do i fetch it?

pearl radish
#

You should consider consulting the documentation for whichever networking solution you're using

shut ridge
#

netcode

pearl radish
#

I said you should, not I'm going to

shut ridge
#

aight bet

spiral geyser
#

I am getting 3 separate NullReferenceException: Object reference not set to an instance of an object errors in my Movement code and I honestly can't figure out why?

shut ridge
#

interesting

#

paste your code

#

or send screenshots

spiral geyser
#

I put it in a pastebin

#

its 209 lines tho so thats why

#

It says the three different errors are at

shut ridge
#

pastebin is giving me errors

spiral geyser
#

lines 72, 104, 187

shut ridge
#

could you paste it fr with the discord formatting system?

#

or dm me it

#

that would be faster

spiral geyser
#

okay I just didn't want to clutter things up

shut ridge
#

thats sensible

#

i suggest dms in that case

spiral geyser
#

I dmed it to you

#

Okay fixed

#

Found the issue: I'm an idiot and didn't put in the right script in the editor

viscid kite
#

is there any performance difference between Transform.Find("") and Transform.GetChild()?

uncut vapor
#

Is it possible to change the highlited, pressed ect. tints in a button through script?

rain minnow
uncut vapor
#

Uh
How
Cuz just button.colors.pressedColor = ... shows an error (can'y modify the value cuz it's not a variable)

viscid kite
#

from what i say, don't use string based searches...but that wasn't from a unity doc so i'm unsure if that's the answer i should've reached

shut ridge
#

getchild is inherently faster

#

bc it is far more efficient compared to find

rain minnow
uncut vapor
#

aand what does assign it back mean

shut ridge
viscid kite
#

got it

rain minnow
rain minnow
rain minnow
shut ridge
rain minnow
shut ridge
#

ah i see

#

my apologies

viscid kite
#

ah yeah whoops meant to say use transform.Find("") so like within scope of the child of the object in question

#

but still yeah noted

dull magnet
#

Hi, I've built a simple script to rotate a camera. This works fine as long as I move the mouse slowly. If I move it too fast, the camera rotation will stutter.

if (mouse.rightButton.wasPressedThisFrame)
{
    rotateStartPosition = mousePosition;
}
if (mouse.rightButton.isPressed)
{
    rotateCurrentPosition = mousePosition;

    Vector3 difference = rotateStartPosition - rotateCurrentPosition;

    rotateStartPosition = rotateCurrentPosition;
    newRotation *= Quaternion.Euler(Vector3.up * (-difference.x));
}

I'm assuming this has to do with difference being too big and skipping a full circle, but clamping it didn't really help. Making it slower with something like difference.x *= 0.5f did mitigate it a bit, but I would hope I could fix it without making it slower. Any advice?

limpid spire
#

I made a new project, and when i tried to create a new workspace with plastic SCM i get this error:
"No connection could be made because the target machine actively refused it."
does anyone know how to fix this?

charred charm
#

Does anyone know why this is happening? Can't build all of a sudden

unreal temple
#

If that fails step back through your commit history until you can find a working commit.

#

And look at the diff

#

See what could be relevant

#

I'd say it's just cache corruption though

#

if it's "all of a sudden"

charred charm
unreal temple
charred charm
#

I tried that, still didn't work unfortunately. And I undid some changes I did and went back to a state where I had a successful build but I still have the same error

#

It's not a big enough project to go through my commit history since I had only very few changes since last commit

#

My thought process is that if it works when I click play in the editor then it shouldn't be any of my few scripts, right?

bronze whale
#

are scriptable objects a good way to save player progress?

gaunt garden
#

I wouldn't say they are particularly suited for it, since for a save state you generally need to write a file to disk

#

ScriptableObjects don't really make that any easier

bronze whale
#

Is there a built in solution for this?

gaunt garden
#

I guess the closest would be PlayerPrefs, but that only works for very simple cases

#

It depends a lot on the project

bronze whale
#

can serialization be used to save progress?

#

Or is that only for saving editor changes

gaunt garden
#

It is usually involved, serialization is just the transformation of an in memory data structure to a stream of something that can be written to a file

#

How that is achieved is up to you

#

I can give you a simple example if you want

bronze whale
#

No thanks

#

I think a json or something would be enough then

gaunt garden
#

Yes, JSON is a common format for save files

bronze whale
#

Cool, thank you

worthy galleon
#

BoxCast doesnt seem to be very consistent in returning true if its hitting something... am I giving it the wrong information here?

hitDetect = Physics.BoxCast(transform.position, transform.localScale, destination, out hitInfo, transform.localRotation, lengthCast);

by my understanding this should shoot out a box with the same size as our player (which is a 0.85x1.275x0.85 box), from our player's position, with our player's rotation (none), and it should go from the center of our player out in the direction 'destination' a total distance of 'lengthCast'

#

im successfully using the information gathered from the BoxCast when it works, the problem is it doesnt seem to actually be able to hit stuff consistently

neat lagoon
#

good for debugging stuff like this 👍

dusk apex
worthy galleon
#

surely i can use BoxCast for collision detection in 3d right?

#

just wanna make sure im not tryin to use the wrong tools

neat lagoon
#

that's what it's for, yes

worthy galleon
#

ok thank god

#

as long as its a user error im ok LOL

#

ty for the tools :3

void basalt
#

I have an issue. I have an abstract class that inherits from mono and uses unity's Start() to do important stuff. If I create a new class and make it inherit from my abstract, it automatically puts the default Start() function inside and overrides the abstract start

#

and screws things up

#

is there a different way that I can get a callback on object initialization? Can't use constructor because of monobehaviour and RuntimeInitializeOnLoadMethod doesn't work on non static methods

leaden solstice
#

override it from child class then call base.Start()

void basalt
#

It's more of just trying to idiot proof it

#

Since it pretty much breaks the entire framework

#

Perhaps I could just use a static class to loop through gameobjects and do my own callbacks at the start

#

I can't find any other solution

leaden solstice
#

Or don't make user inherit from your class at all and use composition instead

void basalt
#

hmm

wild nebula
#

I'm running into a strange rotation issue

#

This is a debug for hlsl shader, I'm trying to do it in C# first.

#
    [ExecuteInEditMode]
    public class ToaTest : MonoBehaviour
    {
        public Transform Target;

        float TOA(float opposite, float adjacent)
        {
            return math.degrees(math.atan(opposite / adjacent));
        }

        void Update()
        {
            if (!Target) return;

            Vector3 deltaPos = transform.position - Target.position;
            float angleX = TOA(deltaPos.y, deltaPos.z);
            float angleY = TOA(deltaPos.x, deltaPos.z);

            Vector3 finalAngle = new Vector3(-angleX, angleY, 0);

            //Debug.Log(finalAngle);

            transform.rotation = Quaternion.Euler(finalAngle);
        }
    }
#

When the angle values are close to 0, it just rotates strangely

#

I can't use lookat because I need to clamp the euler angles to have a min/max rotation.

#

Please help :c

wild nebula
#

So use atan2 instead?

leaden solstice
#

Nah did you see Pitch function

wild nebula
#
        public static float Pitch(Vector3 forward)
        {
            return -MathF.Asin(forward.y) * Rad2Deg;
        }
leaden solstice
#

Yes

wild nebula
#

Ok I'll give it a go

leaden solstice
#

Yaw for Y, Pitch for X in euler

leaden solstice
wild nebula
#

But its jittering right now

#
    [ExecuteInEditMode]
    public class ToaTest : MonoBehaviour
    {
        public Transform Target;

        private Vector3 Forward(Quaternion rotation)
        {
            float x2 = rotation.x * 2f;
            float y2 = rotation.y * 2f;
            float xx2 = rotation.x * x2;
            float yy2 = rotation.y * y2;
            float xz2 = rotation.z * x2;
            float yz2 = rotation.z * y2;
            float xw2 = rotation.w * x2;
            float yw2 = rotation.w * y2;

            return new Vector3(xz2 + yw2, yz2 - xw2, 1.0f - (xx2 + yy2));
        }

        private float Yaw(float opposite, float adjacent)
        {
            return math.degrees(math.atan(opposite / adjacent));
        }

        private float Pitch(Vector3 forward)
        {
            return math.degrees(-math.asin(forward.y));
        }

        void Update()
        {
            if (!Target) return;

            Vector3 deltaPos = transform.position - Target.position;
            //float pitch = Pitch(Forward(math.normalize(transform.rotation)));
            float pitch = Pitch(Forward(transform.rotation));
            float yaw = Yaw(deltaPos.x, deltaPos.z);

            Vector3 finalAngle = new Vector3(-pitch, yaw, 0);

            Debug.Log(finalAngle);

            transform.rotation = Quaternion.Euler(finalAngle);
        }
    }
#

I commented the normalize because I think Forward(quat) is already normalized

#

Whoops my bad

#

I had -pitch

#

That's the whole problem

leaden solstice
wild nebula
#

Swapped Vector3 finalAngle = new Vector3(-pitch, yaw, 0); with Vector3 finalAngle = new Vector3(pitch, yaw, 0); and its smooth :))

#

Thanks so much, it worked really well!

leaden solstice
wild nebula
#

Oh ok

leaden solstice
#

And I think it should be target - position ? but idk your setup 😄

wild nebula
#

I am trying to make a billboard that can be clamped

leaden solstice
#

Oh sure

wild nebula
#

I think there is still a problem when Z value is close to 0

#

Y rotation still jumps

leaden solstice
#

Oh yeah

#

Use atan2

#

For Yaw

leaden solstice
wild nebula
#

It worked!

#

Ah I see

#

Thank you so much

#

I'll try to bring this to shader now :))

leaden solstice
wild nebula
# leaden solstice Sounds fun, good luck! 😄
float Pitch(float3 forward)
{
    return degrees(-asin(forward.y));
}

float Yaw(float opposite, float adjacent)
{
    return degrees(atan2(opposite, adjacent));
}

void TrigBillboard_float(float3 VertexPosition, float3 ObjectScale, float3 ObjectPosition, float3 CameraPosition, float3 MinAngle, float3 MaxAngle, out float3 Out)
{
    float3 scaledVertexPosition = VertexPosition * ObjectScale;
    float3 deltaPos = normalize(CameraPosition - ObjectPosition);

    float pitch = Pitch(deltaPos);
    float yaw = Yaw(deltaPos.x, deltaPos.z);

    float3 eulerDirection = float3(pitch, yaw, 0);

    float4x4 constrainedDir = ToMatrix4x4(eulerDirection);

    float4 rotatedVertex = mul(constrainedDir, float4(scaledVertexPosition.x, scaledVertexPosition.y, scaledVertexPosition.z, 0));
    float3 finalPosition = rotatedVertex + ObjectPosition;

    Out = TransformWorldToObject(finalPosition);
}
#

Worked flawlessly

#

:))

#

Now I just have to clamp them, thanks again!

#

Weeks of headache gone!

rose stag
#

Is there a direct way to make and modify an image within code then display it as a texture?

pine inlet
#

hey fellas, how could i rotate a square(blue in picture) in 2d to sort of align itself with a linerenderer(red in the picture) like images 1 and 3? This is what i have so far but the result is similar to image 2

        Vector2 formationNormal = Vector2.Perpendicular(GetFormationMiddlePoint());
        return formationNormal;
    }

    void SetFormationSquare(){
        formationSquare.transform.position = GetFormationMiddlePoint();
        formationSquare.transform.localScale = new Vector2(GetFormationLength(),1);
        float rot_z = Mathf.Atan2(GetFormationNormal().y, GetFormationNormal().x) * Mathf.Rad2Deg;
        formationSquare.rotation = Quaternion.Euler(0f, 0f, rot_z);
        Debug.Log($"Line normal is {GetFormationNormal()}");
    }```
dusk apex
#

Or do the same with the Euler Angles, quaternion etc.

prime dune
#

hiya chat, i'm wondering if anybody has any advice for the "best" way to go about resetting an enemy after restarting to a checkpoint in my FPS game

prime dune
#

right now when enemies die, they get disabled instead of just destroying

#

i was considering just saving every relevant initial value at Start() but i feel like i might be missing an obvious solution

#

like perhaps a way to just reset a gameobject to its state at scene start?

#

although that's probably easier said than done

rose stag
prime dune
#

the thing with that is that the entire point of the checkpoint system is to let the player just restart to a certain point in the level

rose stag
#

If you want, you could make the checkpoint ID either a static variable or in a DontDestroyOnLoad game object.

#

I had a similar problem when I was making a game jam game and I just reset the entire scene with a public static checkpoint ID.

prime dune
#

i've thought about just instantiating all of the enemies when they spawn instead of just setting them to active

#

but that seems like it could get messy quick

prime dune
#

or i guess script is more apt terming since they're split into their own scripts

rose stag
prime dune
#

i think realistically i'm probably just gonna go with the route of saving all relevant properties at scene start and then just setting everything back to that when they respawn

rose stag
prime dune
#

it just feels messy and unnecessary but that may just be me

#

i'll see what i can do

unreal temple
#

Place spawners in your level instead of enemy prefab instances

#

Then when they spawn chuck em in a list

#

When you hit the checkpoint, destroy anything left in the list, and loop through spawners to respawn

#

Reloading the whole scene is okay too if you can do it seamlessly enough

rose stag
# prime dune i'll see what i can do

If you are curious what I did for my game, here it is. ```cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Checkpoint : MonoBehaviour
{
public static int checkpoint;
[SerializeField] int id;
// Start is called before the first frame update
void Start()
{
if (checkpoint == id)
{
GameObject p = GameObject.Find("Player");
p.transform.position = transform.position;
}
}

// Update is called once per frame
void OnTriggerEnter(Collider col)
{
    if (checkpoint != id && col.name == "Player")
    {
        checkpoint = id;
    }
}

}

I then assigned each checkpoint a unique id in the inspector. This is an old script of mine, I know GameObject.Find("Player") is pretty silly.
prime dune
#

hmmm okay i think i know what i'm gonna try

#

thanks for the advice folks v1thumbsup

severe coral
#

What would be the most efficient way to use a compute shader to edit only a specific region of a texture2d? I don't want to have to send the entire texture through a buffer each time if I only want a fraction of it changed.

#

Look up a state machine, and if that's not complicated enough for your uses look into a behavior tree

#

And if I were in your shoes I'd try to make good use of delegates, I don't think they have any terrible performance drawbacks

swift falcon
#
    {
        object playerName;
        if (PhotonNetwork.LocalPlayer.CustomProperties.TryGetValue("playerculture", out playerName))
        {
            player1Culture=Convert.ToString(playerName);
        }
        Debug.Log(player1Culture);
        Photon.Realtime.Player[] otherPlayers = PhotonNetwork.PlayerList.Where(player => player != PhotonNetwork.LocalPlayer).ToArray();

        foreach (Photon.Realtime.Player otherPlayer in otherPlayers)
        {
            object value;
            if (otherPlayer.CustomProperties.TryGetValue("playerculture", out value))
            {
                otherPlayerCulture = Convert.ToString(value);
            }
        }
        if(PhotonNetwork.IsConnected)
        {
            Game();
        }
    }   

    public void Game()
    {
        TheGame();
    }
    public void TheGame()
    {
        position=Position1;
        Displaytext.text=cultureAspects[0];
        if(PhotonNetwork.IsMasterClient)
        {
            if (player1Culture =="Japanese")
            {
                JapaneseFoodInventory.SetActive(true);              
            }else if (player1Culture =="British")
            {
                BritishFoodInventory.SetActive(true);   
            }else if (player1Culture =="American")
            {
                AmericanFoodInventory.SetActive(true);
            }
        }
        Displaytext.text="Player has chosen an object";
    }
}```
#

Can someone help me with this

#

The problem is

#

the Displaytext.text is getting displayed at the start of the game itself

#

instead of displaying after all the initial code is done

wild nebula
leaden solstice
wild nebula
#

Oh, so like 0, 0, 1 but * rotation

leaden solstice
#

Yes

wild nebula
#

Ok cool :>

#

Is it possible to get the Yaw/Pitch angles from direction vector?

#

Found this

float3 ToEulerXYZ(float3 dir)
{
    float pitch = atan2(-dir.y, sqrt((dir.x * dir.x) + (dir.z * dir.z)));
    float yaw = atan2(dir.x, dir.z);

    return float3(pitch, yaw, 0);
}```
#

Nvm I don't think its right.

leaden solstice
#

Pitch and Yaw function is for it

wild nebula
#

So I'm trying to convert camera inverse matrix to eulers

#

Something like this float3 eulerAngles = ToEulerXYZ(Forward(ToQuaternion(UNITY_MATRIX_I_V)))

#

Then clamp each of their axis.

#

Actually idk anymore brain is fired atm

#
void ConstrainedBillboard_float(float3 VertexPosition, float3 ObjectScale, float3 ObjectPosition, float3 CameraPosition, float2 MinAngle, float2 MaxAngle, out float3 Out)
{
    float3 scaledVertexPosition = VertexPosition * ObjectScale;
    //float3 deltaPos = normalize(CameraPosition - ObjectPosition);
    float3 deltaPos = Forward(ToQuaternion(UNITY_MATRIX_I_V));

    float pitch = clamp(Pitch(deltaPos), MinAngle.x, MaxAngle.x);
    float yaw = clamp(Yaw(deltaPos.x, deltaPos.z), MinAngle.y, MaxAngle.y);
    
    float3 eulerDirection = float3(pitch, yaw, 0);

    float4x4 constrainedDir = ToMatrix4x4(eulerDirection);

    float4 rotatedVertex = mul(constrainedDir, float4(scaledVertexPosition.x, scaledVertexPosition.y, scaledVertexPosition.z, 0));
    float3 finalPosition = rotatedVertex + ObjectPosition;

    Out = TransformWorldToObject(finalPosition);
}
#

I'll come back to it after a while ig @@

pine inlet
#

Alright im back with a different approach that still doesnt work 🤣 , so what i am trying to do is make a square parallel to a line renderer that only has 2 points.
Right now im trying to do this by getting the angle of the line and setting the square rotation to this angle, though it pretty much doesnt work as the rotation is wrong, here's the code i use for setting the rotation:

     Debug.DrawLine(formationLine.GetPosition(0), formationLine.GetPosition(1), Color.red);
     Quaternion angle = Quaternion.FromToRotation(formationLine.GetPosition(0), formationLine.GetPosition(1));
     Debug.Log(angle);
     return angle;
 }
 void SetFormationSquare(){
     formationSquare.transform.position = GetFormationMiddlePoint();
     formationSquare.transform.localScale = new Vector2(GetFormationLength(),1);
     formationSquare.localRotation = GetFormationNormal();
 }```
mental rover
elder totem
#

Is anyone here familiar with photon especially with webgl?

eternal tusk
#

is there a way that you can apply a texture onto a gameobject through C#?

trail torrent
#

Can anyone help me? The error for the code is
"IndexOutOfRangeException: Index was outside the bounds of the array."
and the code is

        for (int x = coord.x - VoxelData.ViewDistanceInChunks; x < coord.x + VoxelData.ViewDistanceInChunks; x++) {
            for (int z = coord.z - VoxelData.ViewDistanceInChunks; z < coord.z + VoxelData.ViewDistanceInChunks; z++) {

                if (isChunkInWorld(coord)) {

                    if (chunks[x, z] == null) << error right here
                        CreateNewChunk(x, z);

                }
            
            }
        }
trail torrent
#

Chunk[,] chunks = new Chunk[VoxelData.WorldSizeInChunks, VoxelData.WorldSizeInChunks];

#

Chunk is my class, imma send it in pastebin

#

if you want

frigid anvil
trail torrent
#

imma put the view distance to 3 since world size in chunks is 8

#

even tho it was 5

frigid anvil
#

The point is that the x is going to start negative, which is out of range for the array.

trail torrent
#

kinda works but if it tries to add something outside the world it does the error

frigid anvil
#

If your world is VoxelData.WorldSizeInChunks, then you want the coordinate reference to be offset from VoxelData.WorldSizeInChunks/2 and cap your view distance using something like Mathf.min(VoxelData.WorldSizeInChunks, coord.x + VoxelData.ViewDistanceInChunks) for instance. It'll need a bit more tweaking to your chunk creation code...

trail torrent
#

ok

#

alright

#

thanks for the help!

frigid anvil
#

Sure!

trail torrent
#

the world is just generating chunks but world size in chunks is a int of the for loop in the start so it can generate it

#

oh i found the error between the line of the error

#

it checks for coord.x, coord.z but it needs to be new ChunkCoord(x, z)

#

x, z is the for loop

mental rover
# pine inlet Any clue how I would get those?

diagram to help- Quaternion.FromToAngle(A, B) is going to give you a rotation from A to B, marked by the grey angle, what you want to find is the rotation from X to AB, marked by the red angle

trail torrent
#

I need help again

craggy nova
#

to be clear this is the code

{
    Debug.Log(isGrounded + "," + canJump);

    if (context.performed && isGrounded && canJump)
    {
        playerRb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
        isGrounded = false;
        canJump = false;
        StartCoroutine(CheckCanJump());
    }
}```
#

when I press Space the character jumps. Do I need to use fixed update for this?

#

I feel like there is no need in this case and none of the tutorials seem to use fixed update for this but I am still not sure

trail torrent
#

Can anyone help me?

simple egret
trail torrent
#

sorry, i just read it and it said to check in the internet and there was nothing about it, just other errors about it

#

basically the error is "IndexOutOfRangeException: Index was outside the bounds of the array." on the AddVoxelDataToChunk line

for (int x = 0; x < VoxelData.ChunkWidth; x++){
            for (int y = 0; y < VoxelData.ChunkHeight; y++){
                for (int z = 0; z < VoxelData.ChunkWidth; z++){

                    AddVoxelDataToChunk(new Vector3(x,y,z));

                }
            }
        }
simple egret
#

You need to read further than the first two lines of that channel!

hollow stone
trail torrent
#

i did

hollow stone
craggy nova
trail torrent
craggy nova
#

oh, you can alter the fixed update frames with timescale right? you mean that?

hollow stone
#

Afaik the input events are invoked by update frames (aka with your frame rate) if you don't choose otherwise or invoke it yourself, thus there might be more or less frames depending on how fast your application runs. Fixed updated are as named a fixed rate that you set in the project settings, it may run more or less fixed frames dependent on how it matches with your normal frame rate. E.g. if you have 30 fixed frames per second and ~60 frames per second you will roughly get 2 fixed frames per render frame, but it might be 0 or 3 or even more if spikes.

hollow stone
craggy nova
hollow stone
craggy nova
#

I do have a cooldown for jump input (.1 seconds) so that shouldn't be a problem

frigid anvil
trail torrent
#
(wrapper managed-to-managed) System.Object.ElementAddr_1(object,int,int,int)
Chunk.CheckVoxel (UnityEngine.Vector3 pos) (at Assets/Scripts/Chunk/Chunk.cs:83)
Chunk.AddVoxelDataToChunk (UnityEngine.Vector3 pos) (at Assets/Scripts/Chunk/Chunk.cs:88)
Chunk.CreateMeshData () (at Assets/Scripts/Chunk/Chunk.cs:52)
Chunk..ctor (ChunkCoord _coord, World _world) (at Assets/Scripts/Chunk/Chunk.cs:34)
World.CreateNewChunk (ChunkCoord coord) (at Assets/Scripts/World/World.cs:117)
World.GenerateWorld () (at Assets/Scripts/World/World.cs:46)
World.Start () (at Assets/Scripts/World/World.cs:25)```
craggy nova
trail torrent
# frigid anvil Okay, so this is going to be when you're first creating the data in the chunk, r...
void AddVoxelDataToChunk(Vector3 pos) {
         for (int p = 0; p < 6; p++){
 
             if (! CheckVoxel(pos + VoxelData.faceChecks[p])) {
                 byte blockID = voxelMap [(int)pos.x,(int)pos.y,(int)pos.z];
                 vertices.Add (pos + VoxelData.voxelVerts[VoxelData.voxelTris[p,0]]);
                 vertices.Add (pos + VoxelData.voxelVerts[VoxelData.voxelTris[p,1]]);
                 vertices.Add (pos + VoxelData.voxelVerts[VoxelData.voxelTris[p,2]]);
                 vertices.Add (pos + VoxelData.voxelVerts[VoxelData.voxelTris[p,3]]);
                 
                 AddTexture(world.blockTypes[blockID].GetTextureID(p));
                 triangles.Add(vertexIndex);
                 triangles.Add(vertexIndex + 1);
                 triangles.Add(vertexIndex+2);
                 triangles.Add(vertexIndex+2);
                 triangles.Add(vertexIndex+1);
                 triangles.Add(vertexIndex+3);
                 vertexIndex += 4;
             }
         }
     }

basically this long code

hollow stone
craggy nova
#

I am actually trying to implement movement right now so I know what you mean

frigid anvil
trail torrent
#

whats wrong with "return world.blockTypes[voxelMap [x,y,z]].isSolid;"? its ok for me

#

but says its not working at times

#

so not ok tbh

frigid anvil
# trail torrent whats wrong with "return world.blockTypes[voxelMap [x,y,z]].isSolid;"? its ok fo...

Well, the result of voxelMap[x, y, z] could be out of range for world.blockTypes or any of x, y, z could be out of range for their relative dimension in voxelMap. What you want to probably do is log the values, so you can see what thing is out of range when it does fail.

From the stack trace
(wrapper managed-to-managed) System.Object.ElementAddr_1(object,int,int,int)
I'm going to guess that one of x, y, z is out of range for voxelMap for some reason. (Because the method being called is ElementAddr (the address of an element of object indexed by three int values, which is your x, y, z parameters to []). So I'd make sure your x, y, z are within the range expected for your array.

trail torrent
#

imma try to fix it

#

oh ok im sorry for this because i might realize what was the problem

#

i had no block types and before i had

#

oh wait no its still not working

desert shard
craggy nova
frigid anvil
trail torrent
frigid anvil
trail torrent
#

oh alright

frigid anvil
#

(Probably after line 82 and before 83 of CheckVoxel from what I'm reading...)

trail torrent
#

idk how to do it but im gonna try to fix it

swift falcon
#

question: I have a script that is attached to multiple game objects in my game and I want to disable that script with one click across all the game objects, is there is a way to link them all in an easy way to be able to disable and enable the script on those game object ? btw there is like 100+ game object that contains that one script

#

also I am trying to disable the script in game mode not in the editor btw lol

#

so its an event that controls if the script should be active on those 100 game objects or not at a specific time

frigid anvil
swift falcon
#

what I am trying to do exactly is, I have a "interactive" script that make game objects interactive to the player but when any animtion clip is running I want all game objects to not be interactive anymore until that clip is over

#

let alone that should happened with every single animation clip that run, so I want an easy way to disable the "interactive" script on everything every time an animtion start

#

other then hard coding it in every single animtion clip

frigid anvil
# swift falcon what I am trying to do exactly is, I have a "interactive" script that make game ...

So...it sounds like you need a central place that the animations are triggered (an AnimationManager essentially) which also knows to tell the script ignore interaction messages and when the animation ends, it tells the script, stop ignoring interaction messages. If the interaction is the 'OnMouseover' kind, then the scripts could just...check a static variable, and return if it's set, so they don't react. I don't like the design, but I also get that it's what you've got, and this approach would work with it...

swift falcon
#

yeah I should try that

#

ty !

weak nacelle
swift falcon
#
    {
        object playerName;
        if (PhotonNetwork.LocalPlayer.CustomProperties.TryGetValue("playerculture", out playerName))
        {
            player1Culture=Convert.ToString(playerName);
        }
        Debug.Log(player1Culture);
        Photon.Realtime.Player[] otherPlayers = PhotonNetwork.PlayerList.Where(player => player != PhotonNetwork.LocalPlayer).ToArray();

        foreach (Photon.Realtime.Player otherPlayer in otherPlayers)
        {
            object value;
            if (otherPlayer.CustomProperties.TryGetValue("playerculture", out value))
            {
                otherPlayerCulture = Convert.ToString(value);
            }
        }
        Game();
    } 

    public void Game()
    {
        TheGame();
    }  
    public async void TheGame()
    {
        position=Position1;
        Displaytext.text=cultureAspects[0];
        if(PhotonNetwork.IsMasterClient)
        {
            if (player1Culture =="Japanese")
            {
                JapaneseFoodInventory.SetActive(true);              
            }else if (player1Culture =="British")
            {
                BritishFoodInventory.SetActive(true);   
            }else if (player1Culture =="American")
            {
                AmericanFoodInventory.SetActive(true);
            }
        }

        while (!flag)
        {
            await Task.Delay(2000);
        }
        await Task.Delay(5000);
        Displaytext.text="Player has chosen an object";
    }
}```
#

Can someone please help me with this. So basically

#

I have 2 players in my game

#

I want the first part of the "TheGame" function to only happen if the player is a masterclient

#

but the rest should happen for all players

#

but the display text is not changing for the second player

#

Is it because the while loop is outside the if condition?

hollow stone
#

I've recently been getting these inspector issues with scripts not loading properly, anyone been noticing something similar? Usually adding a blank line to make the script reload fixes it but not always, but it keeps popping up now and then. Possibly after me splitting the project to a bunch of assemblies.

thorny rock
hollow stone
thorny rock
#

Then it's possible you change it from MonoBehaviour to non-MonoBehaviour and thus you cannot attach the script to a GameObject?

hollow stone
thorny rock
#

Odd 😦

lethal plank
#

guys i have a question

#

what the speed mean in rigridbody?
m/s or km/h?

hasty canopy
thorny rock
lethal plank
hasty canopy
lethal plank
hollow stone
# thorny rock Odd 😦

Does pressing apply on asmdef do anything special? I'm doing some shenanigans where I'm generating my asmdef by text which might be the cause of it?

calm delta
#

how do i get an array of gameobjects of all the objects in the scene that have a script with a specific interface?

simple egret
#

Use FindObjectsOfType and pass the interface as the type argument

#

Returns an array

calm delta
#

that doesn't work

#

i'm looking for an array of GameObject

simple egret
#

Then you need more transformation on the array. Loop over it, and for each item cast it to MonoBehaviour (will fail if the type implementing the interface isn't a MB), and get its gameObject field

#

Or, a smarter way would be to add a property in the interface like this

GameObject gameObject { get; }

Which allows you to get the GameObject directly without casting

#

It works because gameObject is already defined, in MonoBehaviour, which satisfies the interface requirements

calm delta
#

i see, yeah

#

the problem im having now is that it won't allow me to use an interface as the type in FindObjectsOfType

simple egret
#

Ah, so it's not like GetComponent, that doesn't have a type constraint

#

Oh well, you'll have to search for all MonoBehaviour instances and filter them to the ones that implement your interface

calm delta
#

yeah this is what i did, it should work

simple egret
#

You can do if (monoBehaviour is IHealthControl) to type check directly

calm delta
#

ooh thank you

simple egret
#

Eliminates a mistake that if the MonoBehaviour itself doesn't implement the interface, it will still try to find another MonoBehaviour on the same object that does

calm delta
#

got it, yeah

sage latch
calm delta
#

thank you though!

inner escarp
#

Hi guys, I have a bit of an issue i can't really tell why its happening but the objects aren't spawning where i need them too:

    void Start()
    {
        //Already have a list of 15 GameObjects, now a list to hold the 15 positions of those objects
        listOfTargetSpawnLocations = new List<Vector3>();
        for (int i = 0; i < listOfTargets.Count; i++)
        {
            GameObject objectToTakePositionFrom = listOfTargets[i];
            Vector3 objectsPosition = objectToTakePositionFrom.transform.position;
            listOfTargetSpawnLocations.Add(objectsPosition);

            //Deactivate once it's position is recorded so its not visible at start.
            objectToTakePositionFrom.SetActive(false);
        }
        Debug.Log(listOfTargetSpawnLocations.Count);
    }

//Throughout update there are several clauses before SpawnAtRandomTarget is called. When it is, the objects spawn nowhere near the position i have them in and seem to spawn on top of each other.
#
    private void SpawARandomnTarget() {
        GameObject randomObject = listOfTargets[Random.Range(0, listOfTargets.Count)];
        Vector3 randomPosition = listOfTargetSpawnLocations[Random.Range(0, listOfTargetSpawnLocations.Count)];

        //Activate the object and set it in on of 15 random positions
        randomObject.SetActive(true);
        randomObject.transform.position = randomPosition;

        // Find the direction from the object to the player
        Vector3 direction = player.transform.position - randomObject.transform.position;
        Quaternion targetRotation = Quaternion.LookRotation(direction);
        transform.rotation = Quaternion.RotateTowards(transform.rotation, targetRotation, objectRotateTime * Time.deltaTime);
        justSpawned = true;
    }
        private IEnumerator Countdown() {
        for (float t = countDownTimer; t >= 0; t -= Time.deltaTime)
        {
            countDownElapsedTime += Time.deltaTime;
            // Wait until the next frame
            yield return null;
        }
    }
#

I have a bunch of targets on a wall:

#

Everything else executes quite well, just when it gets to here.

#

And i don't understand how the position can move so far, when i'm activating it in its current place, saving its position and then deactivating

#

And then setting its position again at Spawn method

#

Eyyy i don't know why but it works now lol

pallid wasp
#

Hey, I´ve been working on a car controller for some time now and no matter which approach I choose for this, the rigidbody always goes crazy as soon as it hits the collider of the floor. Even if I start a new project, that error is still existent. I also already tried the edy´s vehicle physics, but the result is the same

thorny rock
vague slate
#

Is there any explanation why array is almost fully null?

#

No Error has popped

#

for my null check

#

oh

#

I used i instead j

#

classic mistake

#

😅

hollow stone
unreal temple
#

@hollow stone what is an assembly def generator for?

hollow stone
#

I think I figured it out. Either it was that it was marked only for editor or not auto referenced 🙃

hollow stone
unreal temple
#

Is this the same space ship game?

hollow stone
unreal temple
late wharf
#

is it public static const or public const static?

late lion
late wharf
#

that works

toxic notch
#

How do I reference a namespace from another assembly? I have code in a package that I want to change, and I have a script in the main assets folder of the project. The script uses a namespace. In the package file, I tried using myNamespace at the top and it says it couldnt be found. Any ideas?

leaden solstice
toxic notch
#

Yes

leaden solstice
toxic notch
#

Added

leaden solstice
toxic notch
#

It's not readonly I have modified it

#

I bought it from the asset store

#

Not sure if that differs from like a default unity package

leaden solstice
#

Anyways you need to look into assembly definition if that is the case

toxic notch
#

OK I'll take a look, thanks

desert shard
#

Does particle system stop action callback work if the callback is declared in a scropt attached to a parent of the PS? or must it be declared on the PS object?

warm wren
#

Yesnt

zinc parrot
#

Is there any way to access the origional mesh of a combined mesh?

spring lava
#

I have a problem accesing a datafield
I want to drop items out of my inventory and the amount of items that i am currently holding.
So the itemdropper script works the way that i get the prefab of the item that is currently in the slot of the item that i have pulled outside of the inventory
then i instantiate the prefab and wished position and remove it out of my inventory
all of that works fine
how i get the prefab is by calling the struct ItemSlot that stores the public InventoryItem item
the public InventoryItem item stores all kind of data like rarity and also the prefab. The prefab itself has a Item Pickup Script on it
The Item Pickup Script has a reference to ItemSlot itemSlot and that itemslot has access to the quantity that i want to access, since i want to change the int quantity that exists within all of this, but i want to only change it, whenever i am actively dropping my item out

sage kite
#

so i'm making this school project where u sit on a flying carpet in VR, and i want the carpet to move the direction the player is looking which works, but I can't make the front of the carpet stay as the front without detroyin everythinh

somber nacelle
sage kite
#

i already removed it

cobalt barn
#

How do I paint Terrain with a script, I want to eventually make it randomly generate different textures around the terrain.

This code runs, but it doesn't do anyhting for some reason.
Can some one please help?

using UnityEngine;
using System.Collections;

public class TerrainPainter : MonoBehaviour
{
    public Texture2D texture;
    public float grassTiling = 10.0f;

    Terrain terrain;

    void Start()
    {
        SetTerrain();
    }

    private void SetTerrain()
    {
        // Get the terrain object and the splat map data for the terrain
        terrain = GetComponent<Terrain>();

        TerrainData terrainData = terrain.terrainData;

        int alphaMapWidth = terrainData.alphamapWidth;
        int alphaMapHeight = terrainData.alphamapHeight;

        float[,,] splatmapData = new float[alphaMapWidth, alphaMapHeight, 2];

        for (int y = 0; y < alphaMapHeight; y++)
        {
            for (int x = 0; x < alphaMapWidth; x++)
            {
                float value = Random.Range(0.0f, 1.0f);
                splatmapData[x, y, 0] = value;
            }
        }

        terrainData.SetAlphamaps(0, 0, splatmapData);

        terrain.materialTemplate.SetTexture("_Control", texture);
        terrain.materialTemplate.SetTextureScale("_Control", new Vector2(grassTiling, grassTiling));
    }
}

#

its placed on terrain, with a texture added to the script

rose stag
#

https://hatebin.com/obahcvmcac Any idea how to optimise my rainbow triangle drawing script? I think it's a nice effect but it runs slow at high resolutions. Obviously, I will use MUCH smaller textures than 1024x512, like 64x32, but it would be great to know how to further optimise my script so it doesn't cause lag when I do a bunch of effects like these.

proper oyster
late lion
zinc parrot
#

hmmm ok

austere oriole
#

Hey guys, I'm trying to get 2D top down multiplayer movement work. But for some reason my character isn't moving at all. Here is the script, but I have a feeling that it isn't the scripts fault, let alone the multiplayer part. Maybe it's something I forgot in inspector?

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

public class PlayerMovementController : NetworkBehaviour
{
    public float speed = 5f;
    public GameObject PlayerModel;

    private Vector2 movement;
    public Rigidbody2D rb;
    //private Animator anim;

    void Start()
    {
        PlayerModel.SetActive(false);
        //anim = GetComponent<Animator>();
    }

    void Update()
    {
        if(SceneManager.GetActiveScene().name == "Game")
        {
            if(PlayerModel.activeSelf == false)
            {
                SetPosition();
                PlayerModel.SetActive(true);
            }
            if(isOwned)
            {
            //Runs ProcessInputs after it checked if you have the authority
            ProcessInputs();

                        // Set Animations
            /*anim.SetFloat("Horizontal", x);
            anim.SetFloat("Vertical", y);
            anim.SetFloat("Speed", Mathf.Abs(x) + Mathf.Abs(y));*/
            } 
        }
    }

    public void SetPosition()
    {
        transform.position = new Vector2(Random.Range(-1,1), Random.Range(-1,1));
    }

    void FixedUpdate()
    {
        if(isOwned)
        {
            // Apply Movement
            rb.velocity = new Vector2(movement.x * speed, movement.y * speed);
        }

    }

    void ProcessInputs()
    {
        float moveX = Input.GetAxisRaw("Horizontal");
        float moveY = Input.GetAxisRaw("Vertical");

        movement = new Vector2(moveX, moveY).normalized;
    }
}
austere oriole
#

Solved it

versed rain
#

I'm trying to add camera collision but it doesn't seem to work. My main camera is a child of an empty game object that is used as transform, which is a child of another empty game object, I am thinking that might be the issues. Here is the code.

#
    private void CollideWithWalls()
    {
        RaycastHit hit;
        float distance = cameraObject.nearClipPlane;

        if (Physics.Raycast(transform.position, cameraPivot.transform.forward, out hit, distance))
        {
            if (hit.collider.gameObject.tag == "Wall")
            {
                float distanceToCollision = Vector3.Distance(transform.position, hit.point);
                transform.position = transform.position + cameraPivot.transform.forward * (distanceToCollision - distance);
            }

            // Debug line to visualize the raycast
            Debug.DrawLine(transform.position, hit.point, Color.red);
        }
        else
        {
            // Debug line to visualize the raycast
            Debug.DrawLine(transform.position, transform.position + cameraPivot.transform.forward * distance, Color.green);
        }

        // Print the values of the raycast variables to the console
        Debug.Log("Raycast hit: " + hit);
        Debug.Log("Raycast distance: " + distance);
    }```
quartz folio
#

RaycastHit has a distance field btw

versed rain
#

So should that value be altered or?

quartz folio
#

Just noting that there's no reason to calculate it yourself

versed rain
#

Oooh