Cannot get script from an entity with raycast

var from = this.camera.getPosition();
var to = from.clone();
to.add(this.camera.forward.clone().scale(10));
app.systems.rigidbody.raycastFirst(from, to, function (result) {
    if(result.entity.name === "blockTop" || result.entity.name === "blockBottom" || result.entity.name ===   "blockRight" || result.entity.name === "blockLeft" || result.entity.name === "blockFront" || result.entity.name === "blockBack"){
        target = result.entity.getParent().findByName("Test Block");
        //Here is where the code to lower the blocks health should go...
    }
});

Each block is surrounded by six entities which act as the sides of the block. When one of the sides is hit, the target value is set to the actual block itself. Each block should also have a script telling it how much health is should have. As the player attacks the block, it should start loosing health. The problem is I do not know how to get the health value out of the blocks script.

I have tried:

var blocksHealth = target.script.Block.blockHealth;
//When block is struck by raycast:
blocksHealth -= 1;
if(blocksHealth <= 0){
    target.destroy();
}

And on the script ā€œBlockā€ located on the block itself, in the ā€œinitializeā€ section:

var blockHealth = 100;

It gives me an error:
cannot read property blockHealth of undefined.

What am I doing wrong?

That error message means that there is no property on target.script called Block. Are you sure your script name is Block? Alternatively, are you sure the entity target actually has the Block script assigned to it?

Yes, the script is named ā€œBlockā€ and the block has that script attatched to it.

target.script.Block;

Block is sopposed to be the name of the script correct?

It’s the string passed to pc.scriptCreate. e.g.:

var Block = pc.scriptCreate('block');

In that case, you should do:

var health = entity.script.block.health;

Note the lower case ā€˜b’.

thanks the script is working now, even added a system where the blocks don’t break instantly, but actually have health.

1 Like