#archived-code-general
1 messages · Page 9 of 1
yup
if you press W and A you want to sum the Vectors for W and A and not process them individually
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
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.
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
How are you calling this? Because this should just wait 0.25 seconds and the next frame it should continue.
How come you aren't using Unity's Input system to manage the axis for you?
I never went out of my way to learn the new input system. Initially didn't really need it since it had to be simple movement, but then I wanted a dash which suddenly makes things a lot more complicated and counts the old way I did it as obsolete, else the dash wouldn't work
ahh
Yap, mistakes were made lmao
Doesn't work
Still same effects
it shouldn't be too hard to adopt into your script honestly
Don't rely on Coroutines if you want an accurate timer
Rather create it in Update
Albeit I don't use null since enums don't support null, so I just made a None for every enum
I don't know I've not learnt the new inputsystem
This is an interval/timer I made yesterday that omits the accuracy problems of a coroutine
https://discordapp.com/channels/489222168727519232/497874004401586176/1060489281220657292
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
It's entirely up to you, but I think you'd be surprised when you see how simple the input system is
https://docs.unity3d.com/ScriptReference/Input.GetAxis.html
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 😅
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
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;}
}
This will only work if all the types are the same
Just store it as a GameObject/Object/object
GetType() will give their type
What do you mean? only work if all the types are the same?
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
You got multiple types, right?
new BuildingController<ResourceBuilding>().GetAll(); new BuildingController<ResidenceBuilding>().GetAll();
You can't get them all with the same generic type
?
They are different classes
Oh, you create one for every single type?
Why not store them all in a single controller?
BuildingController<ResourceBuilding> is a type, BuildingController<MilitaryBuiling> is another type
yes, as I mentioned, I can. Now, which one do you choose to get specific types?
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);
}
}
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.
OK, BuildingController it is single
now, I want filter it, I think you did not get my question
dont cache the GameObject cache the component
Agree, you mean base component for buildings?
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?
easy use _buildings[i].GetType().Equals(typeof(type I want));
enum type field inside or checking getcomponent or is checking on BaseBuilding
OK, thanks
It is probably better to just create a list of type Tuple<Type, BaseBuilding> instead of storing the whole gameobject
Because whilst also being sarcastic, this is also not a very good way to handle this problem
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?
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;
}
}
Can you show this code from inside your editor?
target does not exist in the scope of time
sure, but the issue is its in polish and i happened to also fail installing the language from unity
so yea sorry about that
Stop using GetComponent<T>() all the time for the same thing. Do it once and cache the result
- You forgot to set the parameter in
time - Even if you set it correctly, you use the parameter wrong in the coroutine
thats what it looks like
And maybe do some lessons on basic c# because this is somethign you should understand
But I prefer generic BuildingController<T> where T:BaseBuilding, power of generic types. It is neat, clean
You can still do that
i am doing a lot of those
typeof(T) should equal the type you store
theres just a lot to learn
Maybe don't start immediatley with Unity but start smaller, like a regular console application
Nothing wrong with learning before you do the project
im doing both at once honestly, doing lessons and then occasionally trying to work on my floppy bird in unity
You need to learn about scopes
In methods, you cannot access variables of another method defined.
You have to store it in a field
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
okay ill ask there i guess
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
This is the first time I've seen someone post code as a quote
Congrats on that, now read the #854851968446365696 and post it properly
Sorry
Is there a way to open the Itunes library and import MP3 files during runtime?
im trying to add a delay betwean item spawns, like you know how items get spawned from a chest 1 by 1
btw
why is this giving me null refrence?
And Line 47 of Macros is what?
that aint gonna throw a null ref
Functions throwing a null ref :?

ok, then your event is null
like noone is calling it?
no its empty.
no like you have not filled it
An event that has no subscribers will be null, yes
yeah so noone is connected to it
bump
any of you fine lads ever worked with the itunes library and unity together by any chance?
If it's possible to have no subscribers at some point, then you can use ?. (conditional access operator) to invoke the event:
OnGoldChange?.Invoke();
Will not invoke the event if it's null.
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
var array = new int[5];
var val = 100;
for (var i = 0; i < array.Length; i++) {
array[i] = Random.Range(0, val + 1);
}
Array.Sort(array);
for (var i = array.Length - 1; i > 0; i--) {
array[i] -= array[i - 1];
}
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
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;
Hover the red underlined identifier
Ah, your IDE isn't configured properly. Check #854851968446365696
It is though
Is it VSCode?
Unless it unconfigured itself again or smth
No, VS
The rest works fine
Not sure, but double check you have VS set as your external editor in preferences
And maybe regenerate project files
It is I recently redid that because it unconfigured itself randomly
(not sure, I don't use VS)
Yeah looks like a project file failure, where it doesn't include some files in the compilation
I'd def try regenerating project files and restarting VS though
Where is that button again?
below this
this will be weird if it picks 100 first.
And also I think it has a bias towards the start of the array?
My probability skills are lacking so I could be wrong
Regenerated, rebooted both Unity and VS
Still the same
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
I really don't know how it's this broken I didn't do much
Yeah it has a greater range towards the first elements, so it's more likely it'll pick a high number first. Gonna run some stats on it
So everything in here?
I think my approach is pretty much correct wrt distribution, it just needs to make sure that the same value isn't picked twice, which I know how to do but since @spark flower hasn't replied I'm not going to bother writing it out.
yeah
Unity will regenerate it
It's safe to delete anything in library.
just trash the whole folder
I deleted everything in the folder
sweet
Is that not sufficient?
That's sufficient, yeah.
Ah
Now reopen
And reopen VS after I guess
I don't really think this will fix your issue, but it's worth a shot
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
Can you adjust which files get a generated csproj?
Make sure you didn't create a class with the same name yourself. Some of the autoprompts in VS could've done it
That's an option for VSCode
should still cause an error in Unity
thats basicly how i did it aswell
There's a refresh connection button somewhere in VS, which will refresh the solution
yep, same issue in yours.
Only in reverse
Yours will bias towards 100
Yeah it has a high bias towards the start of the array
I do not have a namespace called Ransom nor the classes TimerActions nor So_TimerManager
The closest namespace I've is CustomTimer
Sums for 15k picks: { 741386, 371801, 185540, 92761, 108512 }
Also if this were the case then this'd give an error in Unity as well, no?
(I didn't see this, whoops)
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?
You mean this?
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
This?
Afaik I never touched these checkboxes
Yeah, try checking git packages maybe?
Yeah I was thinking of that, lemme check
nope, because I saind in VS. This button is in Unity.
Ah right
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
Well, it should work either way tbh. But this just forces it to create a csproj for that library.
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
Distribution looks good, though sum never reaches 100 :/
99?
I got one 99, but it's mostly random
oh darn
Well, there's some bug
That's what you get when you code directly into discord I guess
oh wait of course
The final sohuldn't be random.
Ah that might be it
Lemme see if I can break it again
Then see if installing that update will fix it
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
I can't seem to re-break it, so I guess we'll never know
Glorious
The important thing is that you don't need to think about it for some indeterminate amount of time
And then forget how I solved it previously and be stuck with the same problem eventually again 
If I untick the box, and regenerate the project files, does it remove the old ones for the ones that are unticked?
type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
Is there a way to obtain methods including inherited ones?
Perfect 👍
booya
@spark flower you seeing this shit?
I stayed up past my bed time for you
and the dream of a perfect distribution
Need Help Building Upon Dialogue System
didnt quite get it
well, it solves your problem.
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
This code is completely insane
It's the simplest way I could think of to solve the problem 🤷
Very similar to how I do weighted probability
var value = Random.Range(array[i], val - i);
this approach was already discussed above
Yup it's absolutely unbreakable
It will have a biased distribution
#archived-code-general message
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.
I reckon something was busted (caching issue somewhere) and now you've blasted it away through the change.
What kind of sorcery is this, that it only needed to be generated once, and then just can be disposed again after
no more so than this
for (var j = 0; j < i; j++) {
if (value >= array[j]) value++;
}
Perhaps the csproj wasn't properly regenerated when you hit the button
I guess, it's pure sorcery though kek
the name Array doesnt exist in current context it says
using System
Then explain the results
#archived-code-general message
I don't think so - something is just off, anyway I'll just update the package for VS as well since rebreaking is not an option apparantly :p, thanks for the help
no probs, glad I chanced upon a solution
nah, that's not what I look for, but dw I jsut made a recursion with BaseType
The way this works is not super obvious, but it's the same as creating a list of all possible values and then removing the ones you've already selected from it.
you havent even tested this code
but that is not what you are doing
Yes it is
That is exactly what this is doing
no, you are removing any value less than one already selected
You're simply mistaken
What can I say?
It's shifting the selection forward to skip the values that have already been selected.
i dont see how this code is useful it has 3 loops while in my code it has just one
Well the new one version kinda includes regenerations, but we'll never know if it'd have fixed it :P (I had the bottom one before this, also you're welcome for me inverting the colors kek)
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);
Yeah thanks for that :p
var intensifies
Number of loops is not the same as usefulness
@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
it's not for no reason, it's to create an even distribution :-P
What isn't?
optimisation kind
the 20 loops one gives correct resaults aswell
and is modifiable easily
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
That's not an optimization. The results are different based on your one loop verse their 3 loops. The issue here is accuracy . . .
Therefore first is better?
imagine the generation sequence 9,8,8 you will end up with 9,8,9
That sequence is not possible because of this line: var value = random.Next(0, val - i);
they do different thing, comparison is not correct
accuracy is not the issue, its supposed to get random value for each index
exactly
then why are you talking to me?
invader is referring to the distribution bias in your/srp's solution
what about it
100-0, 100-1, 100-2, yes it is
unnececery complicating the code
just to force solve it through an idea
Ah. you're right. It needs to be sorted on each iteration to work correctly.
So that the result would be 9,8,10
exactly
you need to store highest number so far
Perhaps there's a simpler way to structure it.
and if you are going to do that you might as well just restrict your random.range
your suggestion:
var value = Random.Range(array[i], val - i);
consider what happens if the first value picked is 100
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
So your first value is in range [5, 100]?
[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
You need to add git to your Path system variable
I have a guide for this for my team
How do I do it?
oh actually it's not that hard
Just install git-scm
It should do it for you
I have a higher/lower card game that works on exactly this principle
Basically you just need to install git
well your solution is better. I bastardised my solution for weighted select
wrong code
Hm. Can't remember where I used this pattern, but somewhere at some time that made more sense.
You on windows? Install this https://git-scm.com/download/win
i did
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
yeah
You'll need to completely restart unity hub after installed installed @cinder kindle
do i need to launch it
Not just unity
task manager style?
No, unity runs it for you
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
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 ()
You have an extra space at the end
@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;
}
That's working now.
Your URI is wrong
jesus thank you
and you @unreal temple
nice
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);
}
}
}```
You can use vector3.rotatetowards to move the forward direction towards the force
this would work for 2d?
can anyone recommend any good site/program to learn c#
I was just thinking about this more. This solution still gives you a bias towards the high end. On average your first pick will be in the middle, so say ~50, which means every additional number selection is going to be higher than that.
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
no, you are absolutely right, however there are algorithms to mitigate this
Right... Well calling mine 'insane' seems pretty silly when you could have just shown one of these other algorithms
that would have been too easy
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.
int val = 100;
int[] vals = new int[vals.Length] { 0..val }
int length = 100;
...
loop {
int ix = Random.Range(0, length);
int value = vals[is];
length--;
vals[ix] = vals[length];
vals[length] = value;
}
Try that for a maximum of 1000000
np
but you are moving the goal posts, your original code had val at 100
It's irrelevant really. The allocation of 100 is needless
You don't know how many times it will be called
read the code, it doesn't matter
I have, it's the same as mine without the optimisation
And without the bug you found
Which is fixable
it's not the same as your's at all and it addresses your question about distribution
It's the same algorithm, different implementation.
Picking from a set that excludes the previously selected numbers
except mine works and your's doesnt
This is what I had to convert it to be since null doesn't work for enums https://gdl.space/qurimekiwi.cs
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.
Just need to move the call to sort. Yours is pseudocode so it also doesn't "work"
I'd avoid it unless you really need the LFS lock feature for artists
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
Any reason you'd recommend the GUI vs command line? Personal preference or is it better for Unity aspects like Large Files?
Git CLI is notoriously hard to learn and confusing. There are other reasons too but the list is so long I don't know where to start
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
hahaha, I use it exclusively at work, didn't realize that put me in a box 😛
I used to as well
Staging individual lines is a pain in cli, as is cherry pick etc
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)
You should try git fork
I think sourcetree has more features
It's very good
Hm, I like the simplicity of GitHub Desktop
Haven't tried git fork though
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
It's just a layer over cli
Cli knowledge is great still for automation
Build and release pipelines
Etc
Does someone know what is cause of this problem
[4] The message header is corrupted and for security reasons connection will be terminated.
Context?
i dont thinks so. i tried changeing them
What
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
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?
It's weird that you say that you want to search all the connections? Usually you only want to search as few as possible for computation sake but still get the correct result. The most commonly used navigation algorithm is A* which is probably what you want anyway.
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
Mathf.Round takes in what value type
hover over it and see
float
The return value of Round is still float
int
so i need a int return from round
Use RoundToInt
that's the issue
It's just same as (int)Mathf.Round but in prettier form
gotcha thank you
ah i wasnt aware it was an enum. Yea sry for the trouble then >-> But if it works now everythings allright, no ^^
Is there any way i can show my World Space on top of Screen Space?
NumberSummoned = root.Q<Label>("NumberSummoned");
Debug.Log($"tmpOffer is null? {NumberSummoned == null}");
how is this null?
Your UI is looking kinda different, which version are you using?
Ok
found the issue...guess I should have included more code 😭
like 3 lines above that I had an unfixed if statement
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.
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
please don't crosspost. stick to one channel
Yeah forum channel when 😄
SmoothDamp 's velocity is not meant to be used by you
It's return value is position
sry dont fully understand that
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 😦
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
Any idea why a [SerializeField] private Image[] isn't showing in inspector?
the word private
Im 80% sure that needs to be deleted
Should've bet on the 20%
😭
I tried just without private, with public instead and it doesn't change nothing
Do you have any errors in the console
nope
Could you post what using statements you have at the top of the file? You might be referencing the wrong Image type.
Oh yeah you're right lmao
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)
Made this little "extension" for Zenject https://github.com/Telov/Extenject
Any feedback?
The return value. Like
current = Vector2.SmoothDamp(current, target, ref vel, ...)
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.
you can use SOs. make an SO class with a field to hold the (enemy) prefab and create an SO asset for each enemy prefab in your project. now place those SO assets in a list and randomly select an index from the list. use the index to access the SO asset (from the list). finally, access the field from the SO class to instantiate the prefab . . .
then what do i put in the ref vel?
It's just a variable that controlled by SmoothDamp
You don't need to modify or set anything for it, just keep the value as member field
create a gizmo to visually see the distance and direction of the cast . . .
No it didn't actually work heh
As far as I could tell, it didn't change anything
Hey so when I have combined meshes due to them being Static, what data to I have access to from there?
White is the original, green is the final
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
is hits your array? if so, you need to initialize it when a set length. the cast will populate the array with colliders until it fills the array . . .
i don't see where you initialize hits at all in your code. better to use this method as it doesn't generate garbage . . .
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
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?
nope . . .
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...
that is weird. is that the only hit or are there more?
the first hit is always the character itself, which I ignore
unless it hits something else
always returning zero vector for all hits
this looks like the character for all of your hits . . .
oops, you are correct. there is another one with the floor as well one sec
make sure you check if the collider from the RaycastHit is not null before attempting to access it . . .
and ensure the length of the buffer (array) can store the amount of colliders needed . . .
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
you only need to initialize it once, not every time . . .
move the cast position and check if hit.point changes . . .
won't it retain all the old raycast hits?
based on where it's at, it is hitting the floor at 0, 0, 0 world position . . .
can't remember but i believe so. you can clear or empty the list instead . . .
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
yes, that is normal . . .
why is this considered normal?
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 . . .
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
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 . . .
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
yes, but that is only if the collider does not already overlap the capsule at the start of the cast/sweep . . .
yeah, I mean that it should be clear in the comment there
it doesn't cast bc a collider is already occurring . . .
this scenario is not true for every cast method. they can't use that description for RaycastHit.point since it doesn't apply 100% of the time, only for the cast method used as each of them are different . . .
oof
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
yes, use SetActive
lol I am stupid sorry
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?
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
not really a code question.
you need colliders on each bone of the avatar
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?
why would it.. it's not parented to bone
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
input to action is irrelevent for this. depends on the method of jumping.
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
sounds like the colliders aren't setup properly or your logic is flawed, hard to know without much context / code
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
when it comes to netcode, is there a way to identify individual players
like some sort of playerid
Clients all have a client id
how do i fetch it?
You should consider consulting the documentation for whichever networking solution you're using
netcode
I said you should, not I'm going to
aight bet
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?
I put it in a pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
its 209 lines tho so thats why
It says the three different errors are at
pastebin is giving me errors
lines 72, 104, 187
could you paste it fr with the discord formatting system?
or dm me it
that would be faster
okay I just didn't want to clutter things up
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
is there any performance difference between Transform.Find("") and Transform.GetChild()?
Is it possible to change the highlited, pressed ect. tints in a button through script?
Yes, greatly. Did you check the unity docs?
Yep, that's doable . . .
Uh
How
Cuz just button.colors.pressedColor = ... shows an error (can'y modify the value cuz it's not a variable)
i guess which doc? is it their respective page or something else?
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
its less docs and more just how they work
getchild is inherently faster
bc it is far more efficient compared to find
ColorBlock is a struct. You have to store it in a temp variable, change the colors and assign it back . . .
aand what does assign it back mean
finding by name is way slower than finding by index of children
got it
From their descriptions in the unity docs ` Find searches the entire scene(s) and should not be used frequently for performance reasons
Transform.Find searches for a child GameObject of the transform, not through entire scene (as stated in both docs) . . .
Huh? Have you used a struct before? When you assign the temp variable back to the property. This is common . . .
It's not less about the docs, the answer is in the docs, and Transform.Find searches with a string, not an index. The more efficient bc it only searches a GameObject's children, not the entire scene . . .
i meant that the docs don't affect the functionality, they communicate it
That would be confusing bc they were asking about which docs to look at and read . . .
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
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?
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?
Try closing unity, deleting Library/ScriptAssemblies and reopening project
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"
That didn't help, I suppose. That being said, I can play in the Editor just fine, does that give any more information?
I haven't seen that error before. You could try nuking the Bee folder too and see if there's some issue there
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?
are scriptable objects a good way to save player progress?
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
Is there a built in solution for this?
I guess the closest would be PlayerPrefs, but that only works for very simple cases
It depends a lot on the project
can serialization be used to save progress?
Or is that only for saving editor changes
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
Yes, JSON is a common format for save files
Cool, thank you
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
https://github.com/nomnomab/RaycastVisualization I will plug this package
good for debugging stuff like this 👍
You could attempt to visualize the cast using assets such as the above or this https://github.com/vertxxyz/Vertx.Debugging
surely i can use BoxCast for collision detection in 3d right?
just wanna make sure im not tryin to use the wrong tools
that's what it's for, yes
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
Make your Start as protected virtual
override it from child class then call base.Start()
This doesn't fix the original problem of Start becoming hidden in the child class and automatically overriding the functionality of the abstract
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
If you have protected method in parent C# will make warning so
Or don't make user inherit from your class at all and use composition instead
hmm
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
Your pitch calculation may be wrong to use atan
So use atan2 instead?
Nah did you see Pitch function
public static float Pitch(Vector3 forward)
{
return -MathF.Asin(forward.y) * Rad2Deg;
}
Yes
Ok I'll give it a go
Yaw for Y, Pitch for X in euler
Oh and make sure you normalize forward
This is way better, it doesn't go crazy when any axis is close to 0
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
Oh I mean you put forward as your direction
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!
deltaPos.Normalize();
float pitch = Pitch(deltaPos);
This way would be more correct
Oh ok
And I think it should be target - position ? but idk your setup 😄
I am trying to make a billboard that can be clamped
Oh sure
void Update()
{
if (!Target) return;
Vector3 deltaPos = Target.position - transform.position;
deltaPos.Normalize();
float pitch = Pitch(deltaPos);
float yaw = Yaw(deltaPos.x, deltaPos.z);
Vector3 finalAngle = new Vector3(pitch, yaw, 0);
Debug.Log(finalAngle);
transform.rotation = Quaternion.Euler(finalAngle);
}
Swapped
I think there is still a problem when Z value is close to 0
Y rotation still jumps
Because if Z is 0 then you get NaN
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!
That was quick 😄
Is there a direct way to make and modify an image within code then display it as a texture?
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()}");
}```
Using Vectors, you should be able to move towards the expected Vector instead of managing angles https://docs.unity3d.com/ScriptReference/Vector3.MoveTowards.html
Or do the same with the Euler Angles, quaternion etc.
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
will attempt, thanks
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
One alternate easier solution is to reset the entire scene. Without reseting the scene, your solution sounds good.
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
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.
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
currently the checkpoints are their own class and i also have a CheckpointHandler class
or i guess script is more apt terming since they're split into their own scripts
Perhaps the checkpoint handler could be DontDestroyOnLoad. Though I don't know how to check for a scene reload in a DontDestroyOnLoad off the top of my head.
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
Depending on the scale of your game and how much actually needs to reload, it may be the best option.
Destroy all enemies and respawn them
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
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.
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
{
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
What does that Forward() function returns? euler angles/radians?
Forward returns normalized direction vector
Oh, so like 0, 0, 1 but * rotation
Yes
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.
That’s what you’ve been doing tho?
Pitch and Yaw function is for it
I figured lookAt camera's object position isn't exactly billboard behavior. They face camera's inverse forward UNITY_MATRIX_I_V.
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 @@
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();
}```
it looks like you're rotating by the angle between the two points with this code, instead you need to rotate by the angle between the line and the default angle
Is anyone here familiar with photon especially with webgl?
is there a way that you can apply a texture onto a gameobject through C#?
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);
}
}
}
Any clue how I would get those?
How is chunks defined?
Chunk[,] chunks = new Chunk[VoxelData.WorldSizeInChunks, VoxelData.WorldSizeInChunks];
Chunk is my class, imma send it in pastebin
if you want
Oh, actually I guess I didn't need that. So what happens when coord.x is smaller than VoxelData.ViewDistanceInChunks?
The point is that the x is going to start negative, which is out of range for the array.
kinda works but if it tries to add something outside the world it does the error
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...
Sure!
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
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
alright, thanks!
I need help again
Can you (or anyone else) elaborate?
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
Can anyone help me?
You need to ask an actual question, see #854851968446365696 for instructions on how to ask a question.
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));
}
}
}
You need to read further than the first two lines of that channel!
There are different ways to do this. You can do things out of callbacks or you can do it by reading values. I would consider cases what happens with the code if there are more fixed frames per update or less, would you have the correct logical outcome in these cases with modifying physics like this?
i did
Usually says what line of script the error is. So you can start investigating this.
I am lost. Aren't there a fixed amount of frames anyways? Or do you mean if there are more fixed update frames than update frames?
i did investigate but theres nothing i cant fix ebcause i dont know whats wrong
oh, you can alter the fixed update frames with timescale right? you mean that?
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.
Try post more lines of the error then.
so in that case the jump can be triggered twice in the same fixed frame instead of once?
It could be attempted to be triggered, but you have guards with booleans that would make it not.
I do have a cooldown for jump input (.1 seconds) so that shouldn't be a problem
Okay, so this is going to be when you're first creating the data in the chunk, right? So what does AddVoxelDataToChunk look like? Because it sounds like you're doing something in that method that's causing the error. Either that, or you're running old code because you didn't save and restart your game in between.
(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)```
So there are no problems with my code then? Or am I just missing the problem?
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
For this case it works. But for some other case it might not, e.g. continuous thrust upwards by input.
I see. Thanks
I am actually trying to implement movement right now so I know what you mean
Right, so now you can see from the stack trace that the actual bug is in CheckVoxel at line 83.
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
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.
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
That's perfectly fine. Why would you need fixed update? It's a single frame event. (Noice the impulse forcemode)
I thought so as well but you know how it is, especially when you are tired, you just start doubting yourself
Log your x, y, z. Something's wrong there.
Thanks
Using Debug.Log on a bool function doesnt work
What? No, on the line before the array reference, log your x, your y and your z values.
oh alright
(Probably after line 82 and before 83 of CheckVoxel from what I'm reading...)
idk how to do it but im gonna try to fix it
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
Do you want to disable as in the GameObject enable type, or make every script instantly know it's not supposed to do something? The latter could be handled with a static variable that is checked by the meaningful methods of the script.
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
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...
I'd make a disable method on the scripts you want to be disabled and just subscribe the method to a switch method on a static class that can be called from anywhere
{
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?
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.
Usually happens when you have uncompilable code and thus Unity is unable to compile all the C# code. It shouldn't just randomly happen without any compiler issues thought.
It frequently happens without compiler issues x)
Then it's possible you change it from MonoBehaviour to non-MonoBehaviour and thus you cannot attach the script to a GameObject?
No this is my Authoring MB acting up. They have been recently moved to assemblies though if that is an issue.
Odd 😦
Units per second
https://docs.unity3d.com/ScriptReference/Rigidbody-velocity.html explains it well I guess. Check the commented code, it's units.
units mean it will go like 600 x/y/z per sec?
If speed is set to 600 yeah
ohh i got it thanks
thank you too
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?
how do i get an array of gameobjects of all the objects in the scene that have a script with a specific interface?
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
i see, yeah
the problem im having now is that it won't allow me to use an interface as the type in FindObjectsOfType
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
yeah this is what i did, it should work
You can do if (monoBehaviour is IHealthControl) to type check directly
ooh thank you
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
got it, yeah
You can also do this with linq. To me it looks cleaner but that's just preference
List<GameObject> candidates =
FindObjectsOfType<MonoBehaviour>()
.OfType<IHealthControl>()
.Select(mono => mono.gameObject)
.ToList();
oftype always yielded in me getting an empty list for some reason, and the system i have rn works so
thank you though!
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
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
Without properly looking at the code, maybe it's the difference between local position and world position?
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
😅
I disabled my assembly def generator and redownloaded the project. This is the stuff I'm getting which doesn't help very much. It's weird that it complains e.g. "'SpaceCraft.Server.RemoveTeamTriggerTag' is missing the class attribute 'ExtensionOfNativeClass'!" when there is a RemoveTeamTriggerTagAuthoring class instead which seems to be the one that is attached to the gameObject?
I've seen this extension of native class thing before. I think it's because you have a non-monobehavior class attached to a game object as a component.
Possibly caused by a script change or meta file mixup.
Also hi! 👋
@hollow stone what is an assembly def generator for?
I think I figured it out. Either it was that it was marked only for editor or not auto referenced 🙃
Ah nice
I have a script where I set up a template assembly definition x)
Ah I see. Damn you must have a lot of assemblies.
Is this the same space ship game?
Yes, just recently got back to it after releasing Lords & Villeins with Michal : )
Oh nice. Congrats, planning on checking it out soon. Saw potato mcwhiskey playing it the other day. Amazing.
is it public static const or public const static?
Neither. const is always static.
that works
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?
Are you saying you want to reference your main assembly code from your package
Yes
Is the package your own or added from package manager?
Added
Then it’s readonly. You cannot and should not modify it
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
That’s not really UPM package, Unity made it confusing
Anyways you need to look into assembly definition if that is the case
OK I'll take a look, thanks
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?
Yesnt
Is there any way to access the origional mesh of a combined mesh?
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
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
don't crosspost. go back to #💻┃code-beginner and maybe check out #854851968446365696 for what to include when you ask a question.
i already removed it
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
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.
"If you're constantly regenerating a texture at runtime, it may be faster to generate an array of pixel colors and set all of them at once with SetPixels."
If you have a reference to the Mesh assets of the meshes that get combined somewhere else, those should be unmodified.
hmmm ok
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;
}
}
Thank you very much! The code now runs super fast! https://hatebin.com/qkvmwwbrdq
Solved it
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);
}```
RaycastHit has a distance field btw
So should that value be altered or?
Just noting that there's no reason to calculate it yourself
Oooh
