Home > OS >  Interact with float between scripts error
Interact with float between scripts error

Time:07-25

I want to import a float fromm a certain script to another :

the float form the script :

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

public class Ship : MonoBehaviour

{
    public float munitions = 0f;
}

so I did this in my other script :

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

public class Destructable : MonoBehaviour


{
    public Ship munitions;
}

private void OnTriggerEnter2D(Collider2D collision) 
{
    if (!canBeDestroyed)
    {
        return;
    }
    Bullet bullet = collision.GetComponent<Bullet>();
    if (bullet != null)
    {
        if (!bullet.isEnemy)
        {
        Destroy(gameObject);
        Destroy(bullet.gameObject);
        munitions  = 10;
        }
    }
}

But I have the error :

Assets\Destructable.cs(48,13): error CS0019: Operator ' =' cannot be applied to operands of type 'Ship' and 'int

And I don't know why...

Can someone help me please?

Thanks!

CodePudding user response:

You trying to plus to variable with class Ship, but you need to plus to variable which inside "munitions" variable.

munitions.munitions  = 10;

Also, if i were you i would renamed munitions to ship in this line

public Ship munitions;

CodePudding user response:

The error is telling you that you can't add types Ship and int together. What you can do to fix this is write:

munitions.munitions  = 10.0f;

What you were doing before is adding an integer value to your ship class instead of the float variable contained inside it. The code I provided earlier should fix that code.

Next time you try to access a variable from a class keep in mind that you have to use

class.variable

since C# doesn't automatically know what variable you are trying to change.

  •  Tags:  
  • c#
  • Related